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

## 目次

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 ダウンロード

```bash
command
    cd /var/www/html/
    curl -s https://getcomposer.org/installer | php
```

```bash
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 ダウンロード確認

```bash
command
    cd /var/www/html/
    ls -la
```
```bash
output
    composer.phar
```

- CakePHP3 インストール

```bash
command
    cd /var/www/html/
    php composer.phar create-project --prefer-dist cakephp/app blog
```
```bash
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 インストール 確認

```bash
command
    cd /var/www/html/blog/
    ls -la 
```
```bash
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](https://qiita-image-store.s3.amazonaws.com/0/30844/c1fc9a64-93fc-15f5-a547-62122376c315.png)

![hands-on-2.png](https://qiita-image-store.s3.amazonaws.com/0/30844/64f2e3b3-767c-4585-ed6e-64464bccb446.png)


### 1.3 CakePHP3の初期設定
- データベース作成

```bash
command
    psql -U postgres
    postgres=# create database {DB名};
    CREATE DATABASE
```

- データベース接続

```bash
command
    /var/www/html/blog/app/config/app.php
    vim /var/www/html/blog/app/config/app.php
```

```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,

```

- キャッシュファイルのパーミッション設定

```php
    '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](https://qiita-image-store.s3.amazonaws.com/0/30844/68dee7f8-7800-cd1a-9895-fe5dd4327d06.png)


### 1.4 マイグレーション

##### 参考URL
http://book.cakephp.org/3.0/ja/migrations.html

![hands-on-er.png](https://qiita-image-store.s3.amazonaws.com/0/30844/a25607f3-c06e-acc9-7abf-c2bd82241085.png)

- マイグレーションファイル作成

```bash
command
    // accounts テーブル作成
    bin/cake bake migration CreateAccounts name:text description:text username:text password:text created modified
```

```bash
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`
```

```bash
command
    // projects テーブル作成
    bin/cake bake migration CreateProjects account_id:integer name:text description:text created modified
```

```bash
command
    // tasks テーブル作成
    bin/cake bake migration CreateTasks project_id:integer name:text description:text created modified
```

- シードファイル作成

```bash
command
    bin/cake bake seed Accounts
    bin/cake bake seed Projects
    bin/cake bake seed Tasks
```

```bash
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`
```

- シードファイル修正

```bash
command
    vim config/Seeds/AccountsSeed.php
```

```php
vim
    use Cake\Auth\DefaultPasswordHasher;  
```
```php
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'),
          ]
        ];
```

```bash
command
    vim config/Seeds/ProjectsSeed.php
```

```php
vim
    use Cake\ORM\TableRegistry;
```
```php
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'),
          ]
        ];
```


```bash
command
    vim config/Seeds/TasksSeed.php
```
```php
vim
    use Cake\ORM\TableRegistry;
```
```php
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'),
          ],
        ];
```
- マイグレーション

```bash
command
    bin/cake migrations migrate
```
```bash
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
```

- シード

```bash
command
    bin/cake migrations seed --seed AccountsSeed
    bin/cake migrations seed --seed ProjectsSeed
    bin/cake migrations seed --seed TasksSeed
```
```bash
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 コマンド確認

```bash
command
    bin/cake bake
```

```bash
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.
```

```bash
command
    bin/cake bake --help
```

```bash
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 コマンド実行

```bash
command
    bin/cake bake all
```
```bash
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.
```
```bash
command
    bin/cake bake all accounts
```
```bash
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...
    (以下略)
```
```bash
command
    bin/cake bake all projects
    bin/cake bake all tasks
```
![hands-on-4.png](https://qiita-image-store.s3.amazonaws.com/0/30844/b42936c4-246d-cedd-e08b-007d5b65de8f.png)


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