CakePHP Component操作

コンポーネントとは

コントローラの機能を拡張するプログラム

独自コンポーネント

コントローラ

use App\Controller\Component;

ロード
$this->loadComponent('Util');

コンポーネントの使用
$point = $this->Util->getPoint();

コンポーネント

※src\Controller\Component\UtilComponent.php
<?php
namespace App\Controller\Component;
use Cake\Controller\Component;
use Cake\ORM\TableRegistry;

class UtilComponent extends Component
{
  public function startup(){
   $this->Users = TableRegistry::get('users');
  }

  public function getPoint()
  {
   $point = $this->Users
    ->find()
    ->select(['point'])
    ->where(['id' => $_SESSION['Auth']['User']['id']])
    ->hydrate(false)
    ->toList()[0]['point'];
    
   return $point;
  }
}

フラッシュコンポーネント

※コントローラ
$this->loadComponent('Flash');
$this->Flash->set('Test');

※ビュー
<?= $this->Flash->render() ?>

Authコンポーネント

コントローラ

Authコンポーネント追加処理
$this->loadComponent(
 'Auth', [
  'authorize' => ['Controller'],
  'authenticate' => 認証に関する設定
  'loginRedirect' => ログイン後のリダイレクト先
  'logoutRedirect' => ログアウト後のリダイレクト先
  'authError' => 認証エラー時メッセージ
 ]
);

※コントローラ
public function initialize()
{
  parent::initialize();

  $this->loadComponent('RequestHandler');
  $this->loadComponent('Flash');
  $this->loadComponent(
   'Auth', [
    'authorize' => ['Controller'],
    'authenticate' => [
     'Form' => [
      'fields' => [
       'username' => 'username',
       'password' => 'password',
      ]
     ]
    ],
    'loginRedirect' => [
     'controller' => 'Users',
     'action' => 'index',
    ],
    'logoutRedirect' => [
     'controller' => 'Users',
     'action' => 'login',
    ],
    'authError' => 'ログインしてください。',
   ]
  );
}

ログインページ

<div>
 <?= $this->Flash->render('auth') ?>
 <?= $this->Form->create() ?>
  <fieldset>
   <legend>アカウント名 / パスワード</legend>
   <?= $this->Form->input('username') ?>
   <?= $this->Form->input('password') ?>
  </fieldset>
  <?= $this->Form->button(__('送信')); ?>
 <?= $this->Form->end() ?>
</div>

callbackメソッドの実行順序

Controller Component
initialize  
  initialize initialize(array $config)
  beforeFilter beforeFilter(Event $event)
beforeFilter  
  startup startup(Event $event)
action  
  beforeRender beforeRender(Event $event)
beforeRender
  shutdown shutdown(Event $event)
afterFilter  

前の記事

CakePHP Contoler操作

次の記事

CakePHP Behavior操作