LoginSignup
0
0

More than 5 years have passed since last update.

Ext Directはじめました

Posted at

この記事は Sencha Advent Calendar 2013 18日目の記事です。

今回Ext Directを使用してみるにあたって書き留めたものです。
何か誤りがあればご教示ください!

Ext Directとは

ExtJSからサーバーサイドのメソッドを呼び出すことができる便利な仕組み!

目標

GridにExt Directを利用してサーバーから取得したレコードを表示させる。

Ext側

view


Ext.define('MyApp.view.List', {
    extend: 'Ext.grid.Panel',
    alias: 'widget.myapp-list',
    width: 300,
    height: 500,
    store: 'List',
    columns: [{
        dataIndex: 'id',
        width: 100,
        text: '社員番号'
    }, {
        dataIndex: 'name',
        flex: 2,
        text: '名前'
    }, {
        dataIndex: 'sex',
        flex: 1.3,
        text: '性別'
    }, {
        dataIndex: 'age',
        flex: 1,
        text: '年齢'
    }]
});

store

proxyコンフィグのtypeにはdirectを指定、directFnに呼び出したいメソッド名を指定します。


Ext.define('MyApp.store.List', {
    extend: 'Ext.data.Store',
    model: 'MyApp.model.List',
    autoLoad: true,
    proxy: {
        type: 'direct',
        directFn: 'MyAppList.getList',
        reader: {
            type: 'json',
            root: 'items'
        }
    }
});

model


Ext.define('MyApp.model.List', {
    extend: 'Ext.data.Model',
    fields: [
        'id',
        'name',
        'sex',
        'age'
    ]
});

PHP側

appディレクトリと同じ階層にphpディレクトリを作成します。

phpディレクトリの中は以下のような構成になります。

kaisou.png

classes/MyAppList.php

この中にExt Directから呼び出すメソッドを記述します。今回は単純にDBから一覧を取得するメソッドのみ記述しています。

<?php
class MyAppList
{
    public function getList() {

        $_result = array();
        $result = array();
        $rows = array();

        $conn = mysql_connect('host', 'user', 'passowd');
        if (!$conn) {
            return false;
        }
        mysql_select_db('hoge', $conn);

        $sql = 'SELECT * FROM staffs';

        $_result = mysql_query($sql, $conn);
        while ($row = mysql_fetch_array($_result)) {
            array_push($rows, array(
                'id' => $row['id'],
                'name' => $row['name'],
                'role' => $row['role'],
                'sex' => $row['sex'],
                'age' => $row['age']
            ));
        }

        $result['items'] = $rows;

        mysql_close($conn);

        return $result;
    }
}

config.php

config.phpにはExt Directで呼び出すクラス名とメソッドを定義します。

ここでは先ほどのMyAppListクラスのgetListメソッドのみ定義しています。

<?php
$API = array(
    'MyAppList' => array(
        'methods' => array(
            'getList' => array(
                'len' => 0
            )
        )
    )
);

index.html

以下を追記します。

    <script src="php/api.php"></script>

完成

グリッドにDBから取得したレコードが表示されました!やったね!

grid.png

コンソールからの実行

Ext Directで呼び出すメソッドを実装する際は、Web Inspectorのコンソールから直接呼び出してやるとデバッグ比較的楽になります。

terminal.png

あとがき

まだapi.phpとrouter.phpのソースを追えていないので、今後はそこの動きも合わせて学んでいきたいと思っています。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0