2016年4月24日日曜日

cakephp3 ページネーション -- Pagination method --

PHP Ver 5.6.27
CakePHP Ver 3.1.9



cakephp3 ページネーション (Cake\View\Helper\PaginatorHelper)


利用できるメソッド一覧

基本的には以下のように利用する。
$this->Paginator->{methodName}

・templates($templates = null)
    $templates = [
        'nextActive' => '< li class="next">< a rel="next" href="{{url}}">{{text}}< /a>< /li>',
        'nextDisabled' => '< li class="next disabled">< a href="" onclick="return false;">{{text}}< /a>< /li>',
        'prevActive' => '< li class="prev">< a rel="prev" href="{{url}}">{{text}}< /a>< /li>',
        'prevDisabled' => '< li class="prev disabled">< a href="" onclick="return false;">{{text}}< /a>< /li>',
        'counterRange' => '{{start}} - {{end}} of {{count}}',
        'counterPages' => '{{page}} of {{pages}}',
        'first' => '< li class="first">< a href="{{url}}">{{text}}< /a>< /li>',
        'last' => '< li class="last">< a href="{{url}}">{{text}}< /a>< /li>',
        'number' => '< li>< a href="{{url}}">{{text}}< /a>< /li>',
        'current' => '< li class="active">< a href="">{{text}}< /a>< /li>',
        'ellipsis' => '< li class="ellipsis">...< /li>',
        'sort' => '< a href="{{url}}">{{text}}< /a>',
        'sortAsc' => '< a class="asc" href="{{url}}">{{text}}< /a>',
        'sortDesc' => '< a class="desc" href="{{url}}">{{text}}< /a>',
        'sortAscLocked' => '< a class="asc locked" href="{{url}}">{{text}}< /a>',
        'sortDescLocked' => '< a class="desc locked" href="{{url}}">{{text}}< /a>',
    ];

・sort($key, $title = null, array $options = [])
    $key(string)
    $title(string)
    $options = [
        'url' => [],
        'model' => 'defaultModel',
        'escape' => true,
    ];

・sortDir($model = null, array $options = [])
    $model = {modelName}
    $options = [
        'url' => [
            'sort' => 'email',
            'direction' => 'desc',
            'page' => 6,
            'lang' => 'en',
        ]
    ];

・sortKey($model = null, array $options = [])
    $key(string)
    $options = [
        'url' => [
            'sort' => 'email',
            'direction' => 'desc',
            'page' => 6,
            'lang' => 'en',
        ]
    ];

・numbers(array $options = [])
    $options = [
        'before' => {numbers},
        'after' => {numbers},
        'model' => 'defaultModel',
        'modulus' => 8,
        'first' => 'First page',
        'last' => 'Last page',
        'templates' => [
            'active' => 'nextActive',
            'disabled' => 'nextDisabled',
        ],
        'url' => [],
    ];

・prev($title = '<< Previous', array $options = [])
    $title(string)
    $options = [
        'disabledTitle' => {title},         'url' => [],
        'model' => 'defaultModel',
        'escape' => true,
        'templates' => [
            'active' => 'nextActive',
            'disabled' => 'nextDisabled',
        ]
    ];

・next($title = 'Next >>', array $options = [])
    $title(string)
    $options = [
        'disabledTitle' => {title},         'url' => [],
        'model' => 'defaultModel',
        'escape' => true,
        'templates' => [
            'active' => 'nextActive',
            'disabled' => 'nextDisabled',
        ]
    ];

・first($first = '<< first', array $options = [])
    $first(string or int)
    $options = [
        'url' => [],
        'model' => 'defaultModel',
        'escape' => true,
    ];

・last($last = 'last >>', array $options = [])
    $last(string or int)
    $options = [
        'url' => [],
        'model' => 'defaultModel',
        'escape' => true,
    ];

・counter($options = [])
    $options = [
        'model' => 'defaultModel', // デフォルトではPaginatorHelper::defaultModelが呼ばれる
        'format' => 'range' or 'pages' or custom
            custom example: 'Page {{page}} of {{pages}}, showing {{current}} records out of
                {{count}} total, starting on record {{start}}, ending on {{end}}'
        ];

・current($model = null)
    $model = {modelName}

・hasNext($model = null)
    $model = {modelName}

・hasPage($model = null, $page = 1)
    $model = {modelName}
    $page = int
・hasPrev($model = null)
    $model = {modelName}

・options(array $options = [])
    $options = [
        'url' => [
            'sort' => 'email',
            'direction' => 'desc',
            'page' => 6,
            'lang' => 'en',
        ]
    ];

・generateUrl(array $options = [], $model = null, $full = false)
    $options = [
        'page' => null,
        'sort' => null,
        'direction' => null,
        'limit' => null,
    ];
    $model = {modelName}
    $full = boolean

・meta(array $options = [])
    $options = [
        'model' => 'defaultModel', // デフォルトではPaginatorHelper::defaultModelが呼ばれる
        'block' => false or {blockName},
    ];

2016年4月22日金曜日

cakephp3 バリデーション(4)
-- validation of cakephp3 --

PHP Ver 5.6.27
CakePHP Ver 3.1.9


Model

・バリデーションを行いたくない場合

$this->newEntity()、$this->patchEntity()を行うとバリデーションが行われてしまうため、
$this->patchEntity($entity, $this->request->data, ['validate' => false] )とすると
バリデーションを行わない。

但し、これ以外にもバリデーションが行われるメソッドがあるので、そこについては要調査

2016年4月14日木曜日

cakephp3 アクセス時のメソッド呼び出し順

PHP Ver 5.6.27
CakePHP Ver 3.1.9



cakephp3 method 呼び出し順


アクセスした場合、以下のように呼び出される

・Controllerのinitialize()
・ComponentのbeforeFilter()
・ControllerのbeforeFilter()
・Componentのstartup()
・Controllerのaction
・ComponentのbeforeRender()
・ControllerのbeforeRender()
・Componentのshutdown()
・ControllerのafterFilter()



その他(Modelで呼ばれるメソッド)

・Model.initialize
・Model.beforeMarshal
・Model.beforeFind
・Model.buildValidator
・Model.buildRules
・Model.beforeRules
・Model.afterRules
・Model.beforeSave
・Model.afterSave
・Model.afterSaveCommit
・Model.beforeDelete
・Model.afterDelete
・Model.afterDeleteCommit

公式HP:http://book.cakephp.org/3.0/ja/orm/saving-data.html

2016年4月13日水曜日

cakephp3 カスタム HTML ヘルパー -- custom html helper --

PHP Ver 5.6.27
CakePHP Ver 3.1.9



cakephp3 カスタムHTMLヘルパーを使う


設定(src/View/AppView.php)

・ここでは例としてCustomHtmlHelperというクラスを作成
initializeメソッドに追記

----------------------
$this->loadHelper('CustomHtml');
----------------------

ここでHelperが付かないことに注意!



クラス作成(src/View/Helper/CustomHtmlHelper.php)

Cake\View\Helperクラスを継承して作成



利用方法(ctpファイルで利用)

$this->CustomHtml->{MethodName}();
で利用可能

2016年4月11日月曜日

cakephp3 DB トランザクション -- DB transaction --

PHP Ver 5.6.27
CakePHP Ver 3.1.9



cakephp3 DB トランザクション


利用方法(※Controllerに記述を行う場合)
== 単一テーブルの登録・更新 ==
・begin
$this->{Model}->connection()->begin();

・commit
$this->{Model}->connection()->commit();

・rollback
$this->{Model}->connection()->rollback();

== 複数テーブルの登録・更新 ==
use Cake\Datasource\ConnectionManager;

$connection = ConnectionManager::get('default');

$connection->begin();

$connection->commit();

$connection->rollback();


ConnectionManagerで指定している「default」は、config/app.phpの「Datasources」で指定しているものになるが、
固定だとdebug機能がうまく使えなくなってしまうので、以下のようにした方が良いと思われる。

$this->loadModel('{Model}');
$connection = ConnectionManager::get($this->{Model}->defaultConnectionName());


Moelクラスに記述するのは、エラー処理などを考えると個人的に嫌いなので割愛

2016年4月8日金曜日

cakephp3 管理画面 ディレクトリ構成変更

PHP Ver 5.6.27
CakePHP Ver 3.1.9



cakephp3 ディレクトリ構成 変更


設定

・config/routes.php
Router::prefix('{prefixName}', function ($routes) {
    $routes->fallbacks('DashedRoute');
});

Router::scope('/{prefixName}', function ($routes) {
    $routes->connect('/', ['controller' => '{controllerName}', 'action' => '{actionName}', 'prefix' => '{prefixName}']);
});


この設定をすることで、URL: http://example.com/{prefixName} で内部的には
src/Controller/{prefixName}/{ControllerName}.php {actionName} メソッドにアクセスしてくれる。

その他の画面用 Controller も src/Controller/{prefixName}/ 配下に作成し、

$this->Html->link(__('View'), ['controller' => '{anotherControllerName}', 'action' => '{anotherActionName}']])

と記述すれば、自動的に http://example.com/{prefixName}/{anotherControllerName}/{anotherActionName} にアクセスしてくれる

2016年4月7日木曜日

cakephp3 Cookie

PHP Ver 5.6.27
CakePHP Ver 3.1.9



cakephp3 Cookieを使う


設定

・App/Controller/AppController.php

    public function initialize()
    {
        parent::initialize();

        $this->loadComponent('RequestHandler');
        $this->loadComponent('Flash');
        $this->loadComponent('Cookie'); ←この行を追記
    }


$this->Cookie->config([
    'expires' => '+10 days',
    'path' => '/',
    'domain' => 'localhost',
    'secure' => true,
    'key' => 'Security.salt',
    'httpOnly' => true,
    'encryption' => 'aes'
]);

※詳細については http://book.cakephp.org/3.0/en/controllers/components/cookie.html 参照

利用方法

$this->Cookie->write('cookie_name', 'info');
$this->Cookie->read('cookie_name');
$this->Cookie->delete('cookie_name');

2016年4月5日火曜日

cakephp3 バリデーション(3)
-- validation of cakephp3 --

PHP Ver 5.6.27
CakePHP Ver 3.1.9


バリデーション詳細
数字
// 自然数$validator    ->add('input_param', [        'type' => [            'rule' => 'naturalNumber'        ]    ]);
// 範囲$validator    ->add('input_param', [        'range' => [            'rule' => 'range',            1, // min            100 // max        ]    ]);


文字列


// minlength
$validator    ->add('input_param', [        'minLength' => [            'rule' => 'minLength',            1 // min        ]    ]);


// maxlength
$validator    ->add('input_param', [        'maxLength' => [            'rule' => 'maxLength',            100 // max        ]    ]);

// 範囲

$validator    ->add('input_param', [        'length' => [            'rule' => 'lengthBetween',            1, // min            100 // max        ]    ]);

・ascii・boolean・cc(クレジットカード)・compareWith・comparison・containsNonAlphaNumeric・custom・date・datetime・decimal・email・equalTo・extension・fileSize・geoCoordinate・inList・ip・isInteger・latitude・longitude・luhn・mimeType・money・multiple・notBlank・numeric・time・uploadedFile・uploadError・url・utf8・uuid

cakephp3 バリデーション(2)
-- validation of cakephp3 --

PHP Ver 5.6.27
CakePHP Ver 3.1.9


public function validationDefault(Validator $validator)
{
    // フィールドの存在確認
    $validator
        ->requirePresence('field_name', 'create');
        // 新規作成時のみチェックしたい場合は「create」を指定
        // 更新時のみチェックしたい場合は「update」を指定

    // 空を許可
    $validator
        ->allowEmpty('field_name');

    // 空を認めない
    $validator
        ->notEmpty('field_name', 'error message', 'create');
        // 新規作成時のみチェックしたい場合は「create」を指定
        // 更新時のみチェックしたい場合は「update」を指定

    // フィールドが用意されているか
    $validator
        ->hasField('field_name');

    // フィールドのバリデーションルールを削除
    $validator
        ->remove('field_name');

    // バリデーションクラスを追加する
    $validator
        ->provider('custom', 'App\Model\Validation\CustomValidation');

    // 入力チェック
    $validator
        ->add('field_name', [
            'validation_name' => [
                'rule' => ['lengthBetween', 4, 10],
                'message' => 'Error Message'
            ]
        ]);
    //  指定できるルールについてはCakephp バリデーション (3) 参照
    return $validator;
}

2016年4月4日月曜日

AWS EC2 を使ってWordPressの実行環境を構築してみた(5)
(phpMyAdmin install)

1. phpMyAdminのインストール
$ sudo yum install -y phpMyAdmin
2. phpMyAdmin 初期設定
・バックアップ取得
$ sudo cp -a /etc/httpd/conf.d/phpMyAdmin.{conf,conf.bk}

・phpMyAdmin.confの編集
$ sudo vi /etc/httpd/conf.d/phpMyAdmin.conf
--------------------------------

< Directory /usr/share/phpMyAdmin/ >
AddDefaultCharset UTF-8

< IfModule mod_authz_core.c >
# Apache 2.4
< RequireAny >
# Require ip 127.0.0.1 ←この行をコメントアウト
# Require ip ::1 ←この行をコメントアウト
Require all granted ~
--------------------------------


-- Build a WordPress execution environment using the EC2 --
(phpMyAdmin install)


1. phpMyAdmin install
$ sudo yum install -y phpMyAdmin
2. phpMyAdmin Initial setting
・create buckup
$ sudo cp -a /etc/httpd/conf.d/phpMyAdmin.{conf,conf.bk}

・phpMyAdmin.conf edit
$ sudo vi /etc/httpd/conf.d/phpMyAdmin.conf
--------------------------------

< Directory /usr/share/phpMyAdmin/ >
AddDefaultCharset UTF-8

< IfModule mod_authz_core.c >
# Apache 2.4
< RequireAny >
# Require ip 127.0.0.1 ← comment out line
# Require ip ::1 ← comment out line
Require all granted ~
--------------------------------