PHP
CakePHP
cakephp3

CakePHP入門  〜コントローラに関する文法〜

この記事は編集中です。

コントローラで使用する文法をまとめていきます。

//index
$users = $this->Users->find('all');  //find 複数のカラムを持ってくる

//view
$user = $this->Users->get($id);  //get カラムを1個持ってくる
$this->set('user', $user);    //ビューで$user変数を使えるようにする
$this->set(compact('user'));  //上に同義
//add
$user = $this->Posts->newEntity();   //userを新しく作る
//add
    if ($this->request->is('post')) {    //もしリクエストがPOSTだったら
      $post = $this->Posts->patchEntity($user, $this->request->data);   //入力されたデータを$userに格納
      if ($this->Posts->save($post)) {   //Userテーブルに保存
        return $this->redirect(['action'=>'index']);
      } else {
        // error
      }
      return $this->redirect(['action'=>'index']);  //indexにリダイレクト
    }

Flash ヘルパー

フラッシュメッセージを表示する。

<?= $this->Flash->render() //ここに代入 ?>   
$this->Flash->success('Add Success!');   //成功
$this->Flash->error('Add Error!');       //失敗

自動で生成

    public function index()
    {
        $users = $this->paginate($this->Users);
        $this->set('users', $users);
    }

    public function view($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);

        $this->set('user', $user);
    }

    public function add()
    {
        $user = $this->Users->newEntity();
        if ($this->request->is('post')) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
    }

    public function edit($id = null)
    {
        $user = $this->Users->get($id, [
            'contain' => []
        ]);
        if ($this->request->is(['patch', 'post', 'put'])) {
            $user = $this->Users->patchEntity($user, $this->request->getData());
            if ($this->Users->save($user)) {
                $this->Flash->success(__('The user has been saved.'));

                return $this->redirect(['action' => 'index']);
            }
            $this->Flash->error(__('The user could not be saved. Please, try again.'));
        }
        $this->set(compact('user'));
    }

    public function delete($id = null)
    {
        $this->request->allowMethod(['post', 'delete']);
        $user = $this->Users->get($id);
        if ($this->Users->delete($user)) {
            $this->Flash->success(__('The user has been deleted.'));
        } else {
            $this->Flash->error(__('The user could not be deleted. Please, try again.'));
        }

        return $this->redirect(['action' => 'index']);
    }