後で読み返しても、これなんだっけ?となるような書き方の可能性ありますが、CakePHP4を弄ってみて、ざっとメモを残したものを羅列しておきます。
インストール後サーバー起動
bin/cake server
URL : http://localhost:8765/
bakeとprefix
bin/cake bake all users --prefix admin
bin/cake bake controller users --prefix admin
bin/cake bake template users --prefix admin
bin/cake bake model users
Oven
- composerを使ってインストールするのが基本だが、ovenというブラウザでセットアップする方法もある https://github.com/CakeDC/oven
- localhost でサーバーを立ち上げてセットアップするが、ovenというディレクトリ以下にしかインストールできない?

値をブラウザに返してその後の処理をしない
exit("hello");
コントローラーからJSON形式でブラウザに返す
echo json_encode($students); exit;
使おうとしているモデルがどんなか出力
debug($this->loadModel('Articles’));
exit;
AppControllerとか継承するコントローラでまとめてレイアウト変更
use Cake\Event\EventInterface;
public function beforeFilter(EventInterface $event)
{
$this->viewBuilder()->setLayout('admin');
}
cssとjsの書き込み
<?= $this->Html->css(['hoge', 'fuga']); ?>
<?= $this->Html->script(['{CDN}', ['block'=>'script_bottom']); ?>
findと表示
$articles = $this->Articles->find('all')
->order(['Articles.id DESC'])
->limit(3);
<?php foreach($articles as $key => $article): ?>
<?= $article->title ?>
<?= $article->details ?>
<?php endforeach; ?>
Pagination
$articles = $this->Articles->find('all')
->order(['Articles.id DESC'])
$this->set('articles', $this->paginate($articles));
<ul class='pagination'>
<?= $this-Paginator->prev("<<") ?>
<?= $this-Paginator->numbers() ?>
<?= $this-Paginator->prev(">>") ?>
</ul>
Pagination カスタマイズ
// AppView.php の中で
public function initialize()
{
...
$this->loadHelper('Paginator', ['templates' => 'paginator-templates']);
}
Config/paginator-templates.php
Bootstrapに対応させる
<?php
return [
'number' => '<li class="page-item"><a class="page-link" href="{{url}}">{{text}}</a></li>',
'nextActive' => '<li class="page-item"><a class="page-link" href="{{url}}">{{text}}</a></li>',
'nextDisabled' => '<li class="page-item"><a class="page-link" href="{{url}}">{{text}}</a></li>',
'prevActive' => '<li class="page-item"><a class="page-link" href="{{url}}">{{text}}</a></li>',
'prevDisabled' => '<li class="page-item"><a class="page-link" href="{{url}}">{{text}}</a></li>',
'current' => '<li class="page-item active"><a class="page-link" href="{{url}}">{{text}}</a></li>',
];
findを「list」と指定して取得
keyFieldとvalueFieldをそれぞれ指定する場合
$articles = $this->Articles->find('list', ['keyField'=>'name', 'valueField'=>'created'])
idを指定して一つだけ取得(Viewページ作るときなど)
$this->Articles->get($id);
Truncate(文字数指定して長文を切る)
$this->Text->truncate(
$this->details,
220,
[
‘ellipsis’ => ‘...’,
‘extract’ => false
]
)
routeがどうなってるか出力
app_local.phpでDEBUGデバッグモードをfalseにするとスッキリする
bin/cake routes
Routes(adminページ作る時のroutesの設定)
routes.phpで
use Cake\Routing\Router;
Router::prefix('admin', function ($routes) {
// ここのすべてのルートには、 `/admin` というプレフィックスが付きます。
// また、 `'prefix' => 'Admin'` ルート要素が追加されます。
// これは、これらのルートのURLを生成するときに必要になります
$routes->connect('/', ['controller' => 'Users', 'action' => 'index']);
$routes->fallbacks(DashedRoute::class);
});
AppControllerを継承したAdminControllerを作る
initialize()内でAuth追加し、loginをallow
class AdminController extends AppController
{
public function initialize(): void
{
parent::initialize();
$this->loadComponent('RequestHandler');
$this->loadComponent('Flash');
$this->loadComponent('Auth');
$this->Auth->allow(['login']);
loginを準備
src/Controller/Admin/UserController.php にlogin追加。ログイン成功時はindexにリダイレクト
public function login()
{
$user = $this->Auth->identify();
if($user){
$this->Auth->setUser($user);
return $this->redirect(['controller'=>'Users', 'action'=>'index']);
}else{
$this->Flash->error("Incorrect username or password !");
}
}
templates/Admin/Users/login.php にフォーム生成
<?= $this->Form->create(); ?>
<?= $this->Form->control('username'); ?>
<?= $this->Form->control('password'); ?>
<?= $this->Form->submit(); ?>
<?= $this->Form->end(); ?>
class指定などしてBootstrap対応すると
<?= $this->Form->create(); ?>
<?= $this->Form->control('username',[
'label' => 'USER ID',
'class' => 'form-control userInput',
'placeholder' => 'USER ID',
'aria-describedby' => 'usernameHelp'
]); ?>
<?= $this->Form->control('password',[
'label' => 'PASSWORD',
'class' => 'form-control userInput',
'placeholder' => 'PASSWORD'
]); ?>
<?= $this->Form->submit('LOGIN',[
'class'=>'btn btn-primary mt-3'
]); ?>
<?= $this->Form->end(); ?>
Password Hasher
そのままだとパスワードを生で入れるので暗号化。app_local.phpのSECURITY_SALTの値を使うので引越する場合などは一致させる必要あり。
App\Model\Entity\User.php
protected function _setPassword($password)
{
if (strlen($password) > 0) {
return (new DefaultPasswordHasher)->hash($password);
}
}
認証済みのユーザーのプロパティを取得
$this->Auth->user('username')
$id = $this->Auth->user('id');
$user = $this->Users->get($id,[
'contain' => ['Roles','Divisions']
]);
以上(今後も随時追加)
東京造形大学卒業後、マクロメディア(現アドビ)に入社。QAやテクニカルサポートマネージャーとしてFlash、DreamweaverなどのWeb製品を担当。独立後、2007年に虫カゴデザインスタジオ株式会社を設立。2021年東京三鷹を拠点に。最近は、Unity, Unity Netcode for GameObjects, CakePHP, Laravel, ZBrush, Modo, Adobe Substance 3D, Adobe Firefly, Xcode, Apple Vision Pro, Firebaseにフォーカスしています。モバイルアプリ開発情報を主としたブログ「MUSHIKAGO APPS MEMO」の中の人。