cakephp3

CakePHP3勉強会 in Fusic ハンズオン資料 part.1

More than 1 year has passed since last update.

目次

  1. 事前準備
    1. CakePHP3の動作環境構築
    2. CakePHP3のインストール
    3. CakePHP3の初期設定
    4. マイグレーション
  2. bake
  3. Auth
  4. Query Builder

次 CakePHP3勉強会 in Fusic ハンズオン資料 part.2
http://qiita.com/Junkins/items/1e9882c463ce67344da2

1.事前準備

1.1 CakePHP3の動作環境構築

  • PHP5.5.9以上
  • MySQL or Postgres
  • CakePHP3.2系
  • composer
  • git

1.2 CakePHPのインストール

  • composer.phar ダウンロード
command
    cd /var/www/html/
    curl -s https://getcomposer.org/installer | php
output

All settings correct for using Composer
Downloading 1.0.0...

Composer successfully installed to: /var/www/html/htdocs/hands-on/composer.phar
Use it: php composer.phar
  • composer.phar ダウンロード確認
command
    cd /var/www/html/
    ls -la
output
    composer.phar
  • CakePHP3 インストール
command
    cd /var/www/html/
    php composer.phar create-project --prefer-dist cakephp/app blog
output
    nstalling cakephp/app (3.2.4)
      - Installing cakephp/app (3.2.4)
        Loading from cache

    Created project in blog
    Loading composer repositories with package information
    Updating dependencies (including require-dev)
      - Installing aura/installer-default (1.0.0)
        Loading from cache

    (以下略)
  • CakePHP3 インストール 確認
command
    cd /var/www/html/blog/
    ls -la 
output
    合計 124
    drwxrwxr-x 11 .
    drwxrwxr-x  3  ..
    -rw-rw-r--  1  .editorconfig
    -rw-rw-r--  1  .gitattributes
    -rw-rw-r--  1  .gitignore
    -rw-rw-r--  1  .htaccess
    -rw-rw-r--  1  .travis.yml
    -rw-rw-r--  1  README.md
    drwxrwxr-x  2  bin
    -rw-rw-r--  1  composer.json
    -rw-rw-r--  1  composer.lock
    drwxrwxr-x  3  config
    -rw-rw-r--  1  index.php
    drwxrwxrwx  2  logs
    -rw-rw-r--  1  phpunit.xml.dist
    drwxrwxr-x  2  plugins
    drwxrwxr-x  8  src
    drwxrwxr-x  4  tests
    drwxrwxrwx  5  tmp
    drwxrwxr-x 15  vendor
    drwxrwxr-x  5  webroot

MySQlが入ってない場合はエラーメッセージが出力されます。

hands-on-1.png

hands-on-2.png

1.3 CakePHP3の初期設定

  • データベース作成
command
    psql -U postgres
    postgres=# create database {DB名};
    CREATE DATABASE
  • データベース接続
command
    /var/www/html/blog/app/config/app.php
    vim /var/www/html/blog/app/config/app.php
vim
    // Postgresの方は、testのdriverも書き換えてください。
    Datasources' => [
            'default' => [
                'className' => 'Cake\Database\Connection',
                // 'driver' => 'Cake\Database\Driver\Mysql',
                'driver' => 'Cake\Database\Driver\Postgres',
                'persistent' => false,
                'host' => 'localhost',
                /**
                 * CakePHP will use the default DB port based on the driver selected
                 * MySQL on MAMP uses port 8889, MAMP users will want to uncomment
                 * the following line and set the port accordingly
                 */
                //'port' => 'non_standard_port_number',
                'username' => '{username}',
                'password' => '{password}',
                'database' => 'blog',
                'encoding' => 'utf8',
                'timezone' => 'UTC',
                'flags' => [],
                'cacheMetadata' => true,
                'log' => false,

  • キャッシュファイルのパーミッション設定
    'Cache' => [
        'default' => [
            'className' => 'File',
            'path' => CACHE,
            'url' => env('CACHE_DEFAULT_URL', null),
        ],

        /**
         * Configure the cache used for general framework caching.
         * Translation cache files are stored with this configuration.
         * Duration will be set to '+1 year' in bootstrap.php when debug = false
         */
        '_cake_core_' => [ 
            'className' => 'File',
            'prefix' => 'myapp_cake_core_',
            'path' => CACHE . 'persistent/',
            'serialize' => true,
            'duration' => '+2 minutes',
            'url' => env('CACHE_CAKECORE_URL', null),
            'mask' => 0666,
        ],

        /**
         * Configure the cache for model and datasource caches. This cache
         * configuration is used to store schema descriptions, and table listings
         * in connections.
         * Duration will be set to '+1 year' in bootstrap.php when debug = false
         */
        '_cake_model_' => [
            'className' => 'File',
            'prefix' => 'myapp_cake_model_',
            'path' => CACHE . 'models/',
            'serialize' => true,
            'duration' => '+2 minutes',
            'url' => env('CACHE_CAKEMODEL_URL', null),
            'mask' => 0666,
        ],
    ],

hands-on-3.png

1.4 マイグレーション

参考URL

http://book.cakephp.org/3.0/ja/migrations.html

hands-on-er.png

  • マイグレーションファイル作成
command
    // accounts テーブル作成
    bin/cake bake migration CreateAccounts name:text description:text username:text password:text created modified
output

    Welcome to CakePHP v3.2.7 Console
    ---------------------------------------------------------------
    App : src
    Path: /var/www/html/htdocs/hands-on/blog/src/
    PHP : 5.6.18
    ---------------------------------------------------------------

    Creating file /var/www/html/htdocs/hands-on/blog/config/Migrations/20160412142111_CreateAccounts.php
    Wrote `/var/www/html/htdocs/hands-on/blog/config/Migrations/20160412142111_CreateAccounts.php`
command
    // projects テーブル作成
    bin/cake bake migration CreateProjects account_id:integer name:text description:text created modified
command
    // tasks テーブル作成
    bin/cake bake migration CreateTasks project_id:integer name:text description:text created modified
  • シードファイル作成
command
    bin/cake bake seed Accounts
    bin/cake bake seed Projects
    bin/cake bake seed Tasks
output
    Welcome to CakePHP v3.2.7 Console
    ---------------------------------------------------------------
    App : src
    Path: /var/www/html/htdocs/hands-on/blog/src/
    PHP : 5.6.18
    ---------------------------------------------------------------

    Creating file /var/www/html/htdocs/hands-on/blog/config/Seeds/AccountsSeed.php
    Wrote `/var/www/html/htdocs/hands-on/blog/config/Seeds/AccountsSeed.php`
  • シードファイル修正
command
    vim config/Seeds/AccountsSeed.php
vim
    use Cake\Auth\DefaultPasswordHasher;  
vim
    public function run()
    {
        $data = [
          [
              'name'            => 'AccountA',
              'description'     => '',
              'username'        => 'admin',
              'password'        => (new DefaultPasswordHasher)->hash('admin'),
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ]
        ];
command
    vim config/Seeds/ProjectsSeed.php
vim
    use Cake\ORM\TableRegistry;
vim
    public function run()
    {
        $query = TableRegistry::get('Accounts')->find();
        $query
            ->where(['Accounts.name' => 'AccountA'])
            ->select(['id']);
        $accounts = $query->firstOrFail();

        $data = [
          [
              'account_id'      => $accounts->id,
              'name'            => 'ProjectA',
              'description'     => 'ProjectA',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
          [
              'account_id'      => $accounts->id,
              'name'            => 'ProjectB',
              'description'     => 'ProjectB',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
          [
              'account_id'      => $accounts->id,
              'name'            => 'ProjectC',
              'description'     => 'ProjectC',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ]
        ];
command
    vim config/Seeds/TasksSeed.php
vim
    use Cake\ORM\TableRegistry;
vim
    public function run()
    {
        $query = TableRegistry::get('Projects')->find('list' , [
            'keyField'   => 'name',
            'valueField' => 'id'
        ]);
        $projects = $query->toArray();

        $data = [
          [
              'project_id'      => $projects['ProjectA'],
              'name'            => 'TaskA',
              'description'     => '',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
          [
              'project_id'      => $projects['ProjectA'],
              'name'            => 'TaskB',
              'description'     => '',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
          [
              'project_id'      => $projects['ProjectA'],
              'name'            => 'TaskC',
              'description'     => '',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
          [
              'project_id'      => $projects['ProjectB'],
              'name'            => 'TaskD',
              'description'     => '',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
          [
              'project_id'      => $projects['ProjectB'],
              'name'            => 'TaskE',
              'description'     => '',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
          [
              'project_id'      => $projects['ProjectC'],
              'name'            => 'TaskF',
              'description'     => '',
              'created'         => date('Y-m-d H:i:s'),
              'modified'        => date('Y-m-d H:i:s'),
          ],
        ];
  • マイグレーション
command
    bin/cake migrations migrate
output
    Welcome to CakePHP v3.2.7 Console
    ---------------------------------------------------------------
    App : src
    Path: /var/www/html/htdocs/hands-on/blog/src/
    PHP : 5.6.18
    ---------------------------------------------------------------
    using migration path /var/www/html/htdocs/hands-on/blog/config/Migrations
    using seed path /var/www/html/htdocs/hands-on/blog/config/Seeds
    using environment default
    using adapter pgsql
    using database blog

     == 20160412142111 CreateAccounts: migrating
     == 20160412142111 CreateAccounts: migrated 0.0094s

     == 20160412142116 CreateProjects: migrating
     == 20160412142116 CreateProjects: migrated 0.0111s

     == 20160412142121 CreateTasks: migrating
     == 20160412142121 CreateTasks: migrated 0.0074s

    All Done. Took 0.0319s
  • シード
command
    bin/cake migrations seed --seed AccountsSeed
    bin/cake migrations seed --seed ProjectsSeed
    bin/cake migrations seed --seed TasksSeed
output
Welcome to CakePHP v3.2.7 Console
---------------------------------------------------------------
App : src
Path: /var/www/html/htdocs/hands-on/blog/src/
PHP : 5.6.18
---------------------------------------------------------------
using migration path /var/www/html/htdocs/hands-on/blog/config/Migrations
using seed path /var/www/html/htdocs/hands-on/blog/config/Seeds
using environment default
using adapter pgsql
using database blog

 == AccountsSeed: seeding
 == AccountsSeed: seeded 0.0851s

All Done. Took 0.0865s

2. bake

2.1 bake コマンド

参考URL

http://book.cakephp.org/3.0/ja/bake/usage.html

  • bake コマンド確認
command
    bin/cake bake
output
    Welcome to CakePHP v3.2.7 Console
    ---------------------------------------------------------------
    App : src
    Path: /var/www/html/htdocs/hands-on/blog/src/
    PHP : 5.6.18
    ---------------------------------------------------------------
    The following commands can be used to generate skeleton code for your application.

    Available bake commands:

    - all
    - behavior
    - cell
    - component
    - controller
    - fixture
    - form
    - helper
    - mailer
    - migration
    - migration_snapshot
    - model
    - plugin
    - seed
    - shell
    - shell_helper
    - task
    - template
    - test

    By using `cake bake [name]` you can invoke a specific bake task.
command
    bin/cake bake --help
output
    Welcome to CakePHP v3.2.7 Console
    ---------------------------------------------------------------
    App : src
    Path: /var/www/html/htdocs/hands-on/blog/src/
    PHP : 5.6.18
    ---------------------------------------------------------------
    The Bake script generates controllers, models and template files for
    your application. If run with no command line arguments, Bake guides the
    user through the class creation process. You can customize the
    generation process by telling Bake where different parts of your
    application are using command line arguments.

    Usage:
    cake bake.bake [subcommand] [options]

    Subcommands:

    all                 Bake a complete MVC skeleton.
    component           Bake a component class file.
    task                Bake a task class file.
    cell                Bake a cell class file.
    shell_helper        Bake a shell_helper class file.
    model               Bake table and entity classes.
    form                Bake a form class file.
    mailer              Bake a mailer class file.
    template            Bake views for a controller, using built-in or
                        custom templates.
    helper              Bake a helper class file.
    controller          Bake a controller skeleton.
    plugin              Create the directory structure, AppController class
                        and testing setup for a new plugin. Can create
                        plugins in any of your bootstrapped plugin paths.
    test                Bake test case skeletons for classes.
    behavior            Bake a behavior class file.
    fixture             Generate fixtures for use with the test suite. You
                        can use `bake fixture all` to bake all fixtures.
    shell               Bake a shell class file.
    seed                Bake seed class.
    migration_snapshot  Bake migration snapshot class.
    migration           Bake migration class.

    To see help on a subcommand use `cake bake.bake [subcommand] --help`

    Options:

    --help, -h        Display this help.
    --verbose, -v     Enable verbose output.
    --quiet, -q       Enable quiet output.
    --everything      Bake a complete MVC skeleton, using all the available
                      tables. Usage: "bake all --everything"
    --connection, -c  Database connection to use in conjunction with `bake
                      all`. (default: default)
    --force, -f       Force overwriting existing files without prompting.
    --plugin, -p      Plugin to bake into.
    --prefix          Prefix to bake controllers and templates into.
    --theme, -t       The theme to use when baking code. (choices:
                      Bake|Migrations)
  • bake コマンド実行
command
    bin/cake bake all
output
    Welcome to CakePHP v3.2.7 Console
    ---------------------------------------------------------------
    App : src
    Path: /var/www/html/htdocs/hands-on/blog/src/
    PHP : 5.6.18
    ---------------------------------------------------------------
    Bake All
    ---------------------------------------------------------------
    Possible model names based on your database:
    - accounts
    - projects
    - tasks
    Run `cake bake all [name]` to generate skeleton files.
command
    bin/cake bake all accounts
output
    Welcome to CakePHP v3.2.7 Console
    ---------------------------------------------------------------
    App : src
    Path: /var/www/html/htdocs/hands-on/blog/src/
    PHP : 5.6.18
    ---------------------------------------------------------------
    Bake All
    ---------------------------------------------------------------
    One moment while associations are detected.

    Baking table class for Accounts...
    (以下略)
    Baking entity class for Account...
    (以下略)
command
    bin/cake bake all projects
    bin/cake bake all tasks

hands-on-4.png

次 CakePHP3勉強会 in Fusic ハンズオン資料 part.2
http://qiita.com/Junkins/items/1e9882c463ce67344da2