SlideShare uma empresa Scribd logo
1 de 125
究極の
Controllerを目指す
     slywalker
自己紹介
原田 康生 Yasuo Harada
大阪のこっそりPHPer

忍び歩く男 - SLYWALKER
http://d.hatena.ne.jp/slywalker/

Twitter, Wassr, Hatena, GitHub ID
slywalker
自己紹介
原田 康生 Yasuo Harada
大阪のこっそりPHPer

忍び歩く男 - SLYWALKER
http://d.hatena.ne.jp/slywalker/

Twitter, Wassr, Hatena, GitHub ID
slywalker
Controllerの
リファクタリングの
   お話です
お約束の画像
お約束の画像
お約束の画像




Controllerをスリムに!
   Modelを厚く!
具体的に
どうすればいいの?
では、
実際にやってみよう!
前提条件
記事投稿の機能の管理画面です

各ユーザがログインして投稿します

画像もあります
<?php
                                                                                                             �           function edit($id = null) {
class PostsController                                      extends AppController {                           �
                                                                                                             �
                                                                                                                         �
                                                                                                                         �
                                                                                                                                   $conditions = array(
                                                                                                                                    �          'Post.id'=>$id,
�          var $name = 'Posts';                                                                              �           �          �          'Post.user_id'=>$this->Auth->user('id'),
                                                                                                             �           �         );
�          function index() {                                                                                �           �         $post = $this->Post->find('first', compact('conditions'));
�          �          $this->paginate = array(                                                               �           �         if (!$post) {
�          �          �         'conditions'=>array(                                                         �           �          �          $this->Session->setFlash(__('Invalid Post', true));
�          �          �         �           'Post.user_id'=>$this->Auth->user('id'),                         �           �          �          $this->redirect(array('action'=>'index'));
�          �          �         ),                                                                           �           �         }
�          �          );                                                                                     �           �         if (!empty($this->data)) {
�          �          $this->Post->recursive = 0;                                                            �           �          �          if (!$this->data['Post']['image']['error']) {
�          �          $this->set('posts', $this->paginate());                                                �           �          �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�          }                                                                                                 �           �          �          �           move_uploaded_file(
                                                                                                             �           �          �          �           �         $this->data['Post']['image']['tmp_name'],
�          function view($id = null) {                                                                       �           �          �          �           �         WWW_ROOT.'img'.DS.$filename);
�          �          $conditions = array(                                                                   �           �          �          �           $this->data['Post']['image'] = $filename;
�          �          �           'Post.id'=>$id,                                                            �           �          �          } else {
�          �          �           'Post.user_id'=>$this->Auth->user('id'),                                   �           �          �          �           unset($this->data['Post']['image']);
�          �          );                                                                                     �           �          �          }
�          �          $post = $this->Post->find('first', compact('conditions'));                             �           �          �          if ($this->Post->save($this->data)) {
�          �          if (!$post) {                                                                          �           �          �          �           $this->Session->setFlash(__('The Post has been saved', true));
�          �          �           $this->Session->setFlash(__('Invalid Post.', true));                       �           �          �          �           $this->redirect(array('action'=>'index'));
�          �          �           $this->redirect(array('action'=>'index'));                                 �           �          �          } else {
�          �          }                                                                                      �           �          �          �           $this->Session->setFlash(__('The Post could not be saved. Please, try
�          �          $this->set(compact('post'));                                                           again.', true));
�          }                                                                                                 �           �          �          }
                                                                                                             �           �         } else {
�          function add() {                                                                                  �           �          �          $this->data = $post;
�           �           if (!empty($this->data)) {                                                           �           �         }
�           �           �          if (!$this->data['Post']['image']['error']) {                             �           }
�           �           �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�           �           �          �           move_uploaded_file(                                           �         function delete($id = null) {
�           �           �          �           �         $this->data['Post']['image']['tmp_name'],           �         �         $conditions = array(
�           �           �          �           �         WWW_ROOT.'img'.DS.$filename);                       �         �          �          'Post.id'=>$id,
�           �           �          �           $this->data['Post']['image'] = $filename;                     �         �          �          'Post.user_id'=>$this->Auth->user('id'),
�           �           �          } else {                                                                  �         �         );
�           �           �          �           unset($this->data['Post']['image']);                          �         �         $post = $this->Post->find('first', compact('conditions'));
�           �           �          }                                                                         �         �         if (!$post) {
�           �           �          $this->data['Post']['user_id'] = $this->Auth->user('id');                 �         �          �          $this->Session->setFlash(__('Invalid id for Post', true));
�           �           �          $this->Post->create();                                                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          if ($this->Post->save($this->data)) {                                     �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post has been saved',        �         �         if ($this->Post->del($id)) {
true));                                                                                                      �         �          �          $this->Session->setFlash(__('Post deleted', true));
�           �           �          �           $this->redirect(array('action'=>'index'));                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          } else {                                                                  �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post could not be saved.     �         }
Please, try again.', true));
�           �           �          }                                                                         }
�           �           }                                                                                    ?>
�          }
<?php
                                                                                                             �           function edit($id = null) {
class PostsController                                      extends AppController {                           �
                                                                                                             �
                                                                                                                         �
                                                                                                                         �
                                                                                                                                   $conditions = array(
                                                                                                                                    �          'Post.id'=>$id,
�          var $name = 'Posts';                                                                              �           �          �          'Post.user_id'=>$this->Auth->user('id'),
                                                                                                             �           �         );
�          function index() {                                                                                �           �         $post = $this->Post->find('first', compact('conditions'));
�          �          $this->paginate = array(                                                               �           �         if (!$post) {
�          �          �         'conditions'=>array(                                                         �           �          �          $this->Session->setFlash(__('Invalid Post', true));
�          �          �         �           'Post.user_id'=>$this->Auth->user('id'),                         �           �          �          $this->redirect(array('action'=>'index'));
�          �          �         ),                                                                           �           �         }
�          �          );                                                                                     �           �         if (!empty($this->data)) {
�          �          $this->Post->recursive = 0;                                                            �           �          �          if (!$this->data['Post']['image']['error']) {
�          �          $this->set('posts', $this->paginate());                                                �           �          �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�          }                                                                                                 �           �          �          �           move_uploaded_file(
                                                                                                             �           �          �          �           �         $this->data['Post']['image']['tmp_name'],
�          function view($id = null) {                                                                       �           �          �          �           �         WWW_ROOT.'img'.DS.$filename);
�          �          $conditions = array(                                                                   �           �          �          �           $this->data['Post']['image'] = $filename;
�          �          �           'Post.id'=>$id,                                                            �           �          �          } else {
�          �          �           'Post.user_id'=>$this->Auth->user('id'),                                   �           �          �          �           unset($this->data['Post']['image']);
�          �          );                                                                                     �           �          �          }
�          �          $post = $this->Post->find('first', compact('conditions'));                             �           �          �          if ($this->Post->save($this->data)) {
�          �          if (!$post) {                                                                          �           �          �          �           $this->Session->setFlash(__('The Post has been saved', true));




        このControllerが
�          �          �           $this->Session->setFlash(__('Invalid Post.', true));                       �           �          �          �           $this->redirect(array('action'=>'index'));
�          �          �           $this->redirect(array('action'=>'index'));                                 �           �          �          } else {
�          �          }                                                                                      �           �          �          �           $this->Session->setFlash(__('The Post could not be saved. Please, try
�          �          $this->set(compact('post'));                                                           again.', true));
�          }                                                                                                 �           �          �          }
                                                                                                             �           �         } else {
�          function add() {                                                                                  �           �          �          $this->data = $post;
�           �           if (!empty($this->data)) {                                                           �           �         }
�           �           �          if (!$this->data['Post']['image']['error']) {                             �           }
�           �           �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�           �           �          �           move_uploaded_file(                                           �         function delete($id = null) {
�           �           �          �           �         $this->data['Post']['image']['tmp_name'],           �         �         $conditions = array(
�           �           �          �           �         WWW_ROOT.'img'.DS.$filename);                       �         �          �          'Post.id'=>$id,
�           �           �          �           $this->data['Post']['image'] = $filename;                     �         �          �          'Post.user_id'=>$this->Auth->user('id'),
�           �           �          } else {                                                                  �         �         );
�           �           �          �           unset($this->data['Post']['image']);                          �         �         $post = $this->Post->find('first', compact('conditions'));
�           �           �          }                                                                         �         �         if (!$post) {
�           �           �          $this->data['Post']['user_id'] = $this->Auth->user('id');                 �         �          �          $this->Session->setFlash(__('Invalid id for Post', true));
�           �           �          $this->Post->create();                                                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          if ($this->Post->save($this->data)) {                                     �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post has been saved',        �         �         if ($this->Post->del($id)) {
true));                                                                                                      �         �          �          $this->Session->setFlash(__('Post deleted', true));
�           �           �          �           $this->redirect(array('action'=>'index'));                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          } else {                                                                  �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post could not be saved.     �         }
Please, try again.', true));
�           �           �          }                                                                         }
�           �           }                                                                                    ?>
�          }
<?php
class PostsController extends AppController {
� var $name = 'Posts';
}
?>
こうなるまでの
<?php
class PostsController extends AppController {
� var $name = 'Posts';
}
?>
こうなるまでの
<?php
class PostsController extends AppController {
� var $name = 'Posts';
}
?>


            実録公開
※注意
※注意
• あくまでもリファクタリングの例です。
※注意
• あくまでもリファクタリングの例です。
• 必ずしもここまでやれ!
 といったものではありません。
※注意
• あくまでもリファクタリングの例です。
• 必ずしもここまでやれ!
 といったものではありません。

• 用法、用量を守り
 正しくお使いください。
<?php
                                                                                                             �           function edit($id = null) {
class PostsController                                      extends AppController {                           �
                                                                                                             �
                                                                                                                         �
                                                                                                                         �
                                                                                                                                   $conditions = array(
                                                                                                                                    �          'Post.id'=>$id,
�          var $name = 'Posts';                                                                              �           �          �          'Post.user_id'=>$this->Auth->user('id'),
                                                                                                             �           �         );
�          function index() {                                                                                �           �         $post = $this->Post->find('first', compact('conditions'));
�          �          $this->paginate = array(                                                               �           �         if (!$post) {
�          �          �         'conditions'=>array(                                                         �           �          �          $this->Session->setFlash(__('Invalid Post', true));
�          �          �         �           'Post.user_id'=>$this->Auth->user('id'),                         �           �          �          $this->redirect(array('action'=>'index'));
�          �          �         ),                                                                           �           �         }
�          �          );                                                                                     �           �         if (!empty($this->data)) {
�          �          $this->Post->recursive = 0;                                                            �           �          �          if (!$this->data['Post']['image']['error']) {
�          �          $this->set('posts', $this->paginate());                                                �           �          �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�          }                                                                                                 �           �          �          �           move_uploaded_file(
                                                                                                             �           �          �          �           �         $this->data['Post']['image']['tmp_name'],
�          function view($id = null) {                                                                       �           �          �          �           �         WWW_ROOT.'img'.DS.$filename);
�          �          $conditions = array(                                                                   �           �          �          �           $this->data['Post']['image'] = $filename;
�          �          �           'Post.id'=>$id,                                                            �           �          �          } else {
�          �          �           'Post.user_id'=>$this->Auth->user('id'),                                   �           �          �          �           unset($this->data['Post']['image']);
�          �          );                                                                                     �           �          �          }
�          �          $post = $this->Post->find('first', compact('conditions'));                             �           �          �          if ($this->Post->save($this->data)) {
�          �          if (!$post) {                                                                          �           �          �          �           $this->Session->setFlash(__('The Post has been saved', true));
�          �          �           $this->Session->setFlash(__('Invalid Post.', true));                       �           �          �          �           $this->redirect(array('action'=>'index'));
�          �          �           $this->redirect(array('action'=>'index'));                                 �           �          �          } else {
�          �          }                                                                                      �           �          �          �           $this->Session->setFlash(__('The Post could not be saved. Please, try
�          �          $this->set(compact('post'));                                                           again.', true));
�          }                                                                                                 �           �          �          }
                                                                                                             �           �         } else {
�          function add() {                                                                                  �           �          �          $this->data = $post;
�           �           if (!empty($this->data)) {                                                           �           �         }
�           �           �          if (!$this->data['Post']['image']['error']) {                             �           }
�           �           �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�           �           �          �           move_uploaded_file(                                           �         function delete($id = null) {
�           �           �          �           �         $this->data['Post']['image']['tmp_name'],           �         �         $conditions = array(
�           �           �          �           �         WWW_ROOT.'img'.DS.$filename);                       �         �          �          'Post.id'=>$id,
�           �           �          �           $this->data['Post']['image'] = $filename;                     �         �          �          'Post.user_id'=>$this->Auth->user('id'),
�           �           �          } else {                                                                  �         �         );
�           �           �          �           unset($this->data['Post']['image']);                          �         �         $post = $this->Post->find('first', compact('conditions'));
�           �           �          }                                                                         �         �         if (!$post) {
�           �           �          $this->data['Post']['user_id'] = $this->Auth->user('id');                 �         �          �          $this->Session->setFlash(__('Invalid id for Post', true));
�           �           �          $this->Post->create();                                                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          if ($this->Post->save($this->data)) {                                     �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post has been saved',        �         �         if ($this->Post->del($id)) {
true));                                                                                                      �         �          �          $this->Session->setFlash(__('Post deleted', true));
�           �           �          �           $this->redirect(array('action'=>'index'));                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          } else {                                                                  �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post could not be saved.     �         }
Please, try again.', true));
�           �           �          }                                                                         }
�           �           }                                                                                    ?>
�          }
<?php
                                                                                                             �           function edit($id = null) {
class PostsController                                      extends AppController {                           �
                                                                                                             �
                                                                                                                         �
                                                                                                                         �
                                                                                                                                   $conditions = array(
                                                                                                                                    �          'Post.id'=>$id,
�          var $name = 'Posts';                                                                              �           �          �          'Post.user_id'=>$this->Auth->user('id'),
                                                                                                             �           �         );
�          function index() {                                                                                �           �         $post = $this->Post->find('first', compact('conditions'));
�          �          $this->paginate = array(                                                               �           �         if (!$post) {
�          �          �         'conditions'=>array(                                                         �           �          �          $this->Session->setFlash(__('Invalid Post', true));
�          �          �         �           'Post.user_id'=>$this->Auth->user('id'),                         �           �          �          $this->redirect(array('action'=>'index'));
�          �          �         ),                                                                           �           �         }
�          �          );                                                                                     �           �         if (!empty($this->data)) {
�          �          $this->Post->recursive = 0;                                                            �           �          �          if (!$this->data['Post']['image']['error']) {
�          �          $this->set('posts', $this->paginate());                                                �           �          �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];




                       さて、
�          }                                                                                                 �           �          �          �           move_uploaded_file(
                                                                                                             �           �          �          �           �         $this->data['Post']['image']['tmp_name'],
�          function view($id = null) {                                                                       �           �          �          �           �         WWW_ROOT.'img'.DS.$filename);
�          �          $conditions = array(                                                                   �           �          �          �           $this->data['Post']['image'] = $filename;
�          �          �           'Post.id'=>$id,                                                            �           �          �          } else {
�          �          �           'Post.user_id'=>$this->Auth->user('id'),                                   �           �          �          �           unset($this->data['Post']['image']);
�          �          );                                                                                     �           �          �          }
�          �          $post = $this->Post->find('first', compact('conditions'));                             �           �          �          if ($this->Post->save($this->data)) {
�          �          if (!$post) {                                                                          �           �          �          �           $this->Session->setFlash(__('The Post has been saved', true));
�          �          �           $this->Session->setFlash(__('Invalid Post.', true));                       �           �          �          �           $this->redirect(array('action'=>'index'));




                  Bad cake の中身を
�          �          �           $this->redirect(array('action'=>'index'));                                 �           �          �          } else {
�          �          }                                                                                      �           �          �          �           $this->Session->setFlash(__('The Post could not be saved. Please, try
�          �          $this->set(compact('post'));                                                           again.', true));
�          }                                                                                                 �           �          �          }
                                                                                                             �           �         } else {
�          function add() {                                                                                  �           �          �          $this->data = $post;
�           �           if (!empty($this->data)) {                                                           �           �         }
�           �           �          if (!$this->data['Post']['image']['error']) {                             �           }
�           �           �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�           �           �          �           move_uploaded_file(




                      見てみる
                                                                                                             �         function delete($id = null) {
�           �           �          �           �         $this->data['Post']['image']['tmp_name'],           �         �         $conditions = array(
�           �           �          �           �         WWW_ROOT.'img'.DS.$filename);                       �         �          �          'Post.id'=>$id,
�           �           �          �           $this->data['Post']['image'] = $filename;                     �         �          �          'Post.user_id'=>$this->Auth->user('id'),
�           �           �          } else {                                                                  �         �         );
�           �           �          �           unset($this->data['Post']['image']);                          �         �         $post = $this->Post->find('first', compact('conditions'));
�           �           �          }                                                                         �         �         if (!$post) {
�           �           �          $this->data['Post']['user_id'] = $this->Auth->user('id');                 �         �          �          $this->Session->setFlash(__('Invalid id for Post', true));
�           �           �          $this->Post->create();                                                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          if ($this->Post->save($this->data)) {                                     �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post has been saved',        �         �         if ($this->Post->del($id)) {
true));                                                                                                      �         �          �          $this->Session->setFlash(__('Post deleted', true));
�           �           �          �           $this->redirect(array('action'=>'index'));                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          } else {                                                                  �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post could not be saved.     �         }
Please, try again.', true));
�           �           �          }                                                                         }
�           �           }                                                                                    ?>
�          }
PostsController::index()
�   function index() {
�   � $this->paginate = array(
�   � � 'conditions'=>array(
�   � � � 'Post.user_id'=>$this->Auth->user('id'),
�   � � ),
�   � );
�   � $this->Post->recursive = 0;
�   � $this->set('posts', $this->paginate());
�   }
PostsController::index()
�   function index() {     user_idで絞り込み
�   � $this->paginate = array(
�   � � 'conditions'=>array(
�   � � � 'Post.user_id'=>$this->Auth->user('id'),
�   � � ),
�   � );
�   � $this->Post->recursive = 0;
�   � $this->set('posts', $this->paginate());
�   }
PostsController::view()
function view($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post.', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   $this->set(compact('post'));
}
PostsController::view()
                                   user_idで絞り込み
function view($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post.', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   $this->set(compact('post'));
}
PostsController::add()
function add() {
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �    $this->data['Post']['user_id'] = $this->Auth->user('id');
PostsController::add()
function add() {
                                         FileUpload処理
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �    $this->data['Post']['user_id'] = $this->Auth->user('id');
PostsController::add()
function add() {
                                         FileUpload処理
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �    $this->data['Post']['user_id'] = $this->Auth->user('id');


                                          user_idの付与
PostsController::add()
�   �    $this->Post->create();
�   �    if ($this->Post->save($this->data)) {
�   �    �    $this->Session->setFlash(__('The Post has been saved', true));
�   �    �    $this->redirect(array('action'=>'index'));
�   �    } else {
�   �    �    $this->Session->setFlash(__('The Post could not be saved.
Please, try again.', true));
�   �    }
�   }
}
PostsController::edit()

function edit($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
PostsController::edit()
                                       user_idで絞り込み
function edit($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
PostsController::edit()

�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
PostsController::edit()
                                         FileUpload処理
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
PostsController::edit()
�   �    if ($this->Post->save($this->data)) {
�   �    �    $this->Session->setFlash(__('The Post has been saved', true));
�   �    �    $this->redirect(array('action'=>'index'));
�   �    } else {
�   �    �    $this->Session->setFlash(__('The Post could not be saved.
Please, try again.', true));
�   �    }
�   } else {
�   �    $this->data = $post;
�   }
}
PostsController::delete()
function delete($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid id for Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   if ($this->Post->del($id)) {
�   �    $this->Session->setFlash(__('Post deleted', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
}
PostsController::delete()
function delete($id = null) {              user_idで絞り込み
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid id for Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   if ($this->Post->del($id)) {
�   �    $this->Session->setFlash(__('Post deleted', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
}
Model へ…
Modelに移すときの
       私的原則
各メソッドで共通の検索条件

$this->data の繰作
今回の場合は
各メソッドで共通の検索条件

• user_idの絞り込み
$this->data の繰作

• user_idの付与
• FileUpload
user_idの絞り込み

Model::beforeFind()を使う

user_idをModelにどうやって渡す?

• Configure::write()
• Configure::read()
PostsController::beforeFilter()


function beforeFilter() {
� parent::beforeFilter();
� Configure::write('User.id', $this->Auth->user('id'));
}
PostsController::beforeFilter()

                           user_idを書き込み
function beforeFilter() {
� parent::beforeFilter();
� Configure::write('User.id', $this->Auth->user('id'));
}
Post::beforeFind()
function beforeFind($queryData) {
�   $conditions = array(
�   �   $this->alias.'.user_id'=>Configure::read('User.id'),
�   );
�   $queryData['conditions'] =
  �     Set::merge($queryData['conditions'], $conditions);
�   return $queryData;
}
Post::beforeFind()
                                       user_idを読み出し
function beforeFind($queryData) {
�   $conditions = array(
�   �   $this->alias.'.user_id'=>Configure::read('User.id'),
�   );
�   $queryData['conditions'] =
  �     Set::merge($queryData['conditions'], $conditions);
�   return $queryData;
}
Post::beforeFind()
                                       user_idを読み出し
function beforeFind($queryData) {
�   $conditions = array(
�   �   $this->alias.'.user_id'=>Configure::read('User.id'),
�   );
�   $queryData['conditions'] =
  �     Set::merge($queryData['conditions'], $conditions);
�   return $queryData;
}
     conditionsは多次元配列になりえる
        ので、Set::merge()を使う
PostsController::index()
�   function index() {
�   � $this->paginate = array(
�   � � 'conditions'=>array(
�   � � � 'Post.user_id'=>$this->Auth->user('id'),
�   � � ),
�   � );
�   � $this->Post->recursive = 0;
�   � $this->set('posts', $this->paginate());
�   }
PostsController::index()
�   function index() {
�   � $this->paginate = array(
�   � � 'conditions'=>array(
�   � � � 'Post.user_id'=>$this->Auth->user('id'),
�   � � ),
�   � );
�   � $this->Post->recursive = 0;
�   � $this->set('posts', $this->paginate());
�   }
PostsController::index()
�   function index() {
�   � $this->paginate = array(
�   � � 'conditions'=>array(
�   � � � 'Post.user_id'=>$this->Auth->user('id'),
�   � � ),
�   � );
�   � $this->Post->recursive = 0;
�   � $this->set('posts', $this->paginate());
�   }
PostsController::view()
function view($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post.', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   $this->set(compact('post'));
}
PostsController::view()
function view($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post.', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   $this->set(compact('post'));
}
PostsController::view()
function view($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post.', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   $this->set(compact('post'));
}
PostsController::edit()

function edit($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
PostsController::edit()

function edit($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
PostsController::edit()

function edit($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
PostsController::delete()
function delete($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid id for Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   if ($this->Post->del($id)) {
�   �    $this->Session->setFlash(__('Post deleted', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
}
PostsController::delete()
function delete($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid id for Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   if ($this->Post->del($id)) {
�   �    $this->Session->setFlash(__('Post deleted', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
}
PostsController::delete()
function delete($id = null) {
�   $conditions = array(
�   �    'Post.id'=>$id,
�   �    'Post.user_id'=>$this->Auth->user('id'),
�   );
�   $post = $this->Post->find('first', compact('conditions'));
�   if (!$post) {
�   �    $this->Session->setFlash(__('Invalid id for Post', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   if ($this->Post->del($id)) {
�   �    $this->Session->setFlash(__('Post deleted', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
}
user_idの付与
Model::beforeValidate()を使う

Configure::read()を使う
Post::beforeValidate()

function beforeValidate($options = array()) {
�   $this->data[$this->alias]['user_id'] = Configure::read('User.id');
�   return true;
}
Post::beforeValidate()
                                             user_idを読み出し

function beforeValidate($options = array()) {
�   $this->data[$this->alias]['user_id'] = Configure::read('User.id');
�   return true;
}
PostsController::add()
function add() {
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �    $this->data['Post']['user_id'] = $this->Auth->user('id');
PostsController::add()
function add() {
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �    $this->data['Post']['user_id'] = $this->Auth->user('id');
PostsController::add()
function add() {
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �    $this->data['Post']['user_id'] = $this->Auth->user('id');
FileUpload

Model::beforeSave()を使う
Post::beforeSave()

function beforeSave($options = array()) {
�   if (!$this->data[$this->alias]['image']['error']) {
�   �    $filename =
  �      �    low($this->alias).DS.$this->data[$this->alias]['image']['name'];
�   �    move_uploaded_file(
�   �    �    $this->data[$this->alias]['image']['tmp_name'],
�   �    �    WWW_ROOT.'img'.DS.$filename);
�   �    $this->data[$this->alias]['image'] = $filename;
�   } else {
�   �    unset($this->data[$this->alias]['image']);
�   }�
�   return true;
}
Post::beforeSave()
                                               FileUpload処理
function beforeSave($options = array()) {
�   if (!$this->data[$this->alias]['image']['error']) {
�   �    $filename =
  �      �    low($this->alias).DS.$this->data[$this->alias]['image']['name'];
�   �    move_uploaded_file(
�   �    �    $this->data[$this->alias]['image']['tmp_name'],
�   �    �    WWW_ROOT.'img'.DS.$filename);
�   �    $this->data[$this->alias]['image'] = $filename;
�   } else {
�   �    unset($this->data[$this->alias]['image']);
�   }�
�   return true;
}
PostsController::add()
function add() {
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �
PostsController::add()
function add() {
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �
PostsController::add()
function add() {
�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
�   �
PostsController::edit()

�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
PostsController::edit()

�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
PostsController::edit()

�   if (!empty($this->data)) {
�   �    if (!$this->data['Post']['image']['error']) {
�   �    �    $filename = 'post'.DS.$this->data['Post']['image']['name'];
�   �    �    move_uploaded_file(
�   �    �    �    $this->data['Post']['image']['tmp_name'],
�   �    �    �    WWW_ROOT.'img'.DS.$filename);
�   �    �    $this->data['Post']['image'] = $filename;
�   �    } else {
�   �    �    unset($this->data['Post']['image']);
�   �    }
<?php
                                                                                                             �           function edit($id = null) {
class PostsController                                      extends AppController {                           �
                                                                                                             �
                                                                                                                         �
                                                                                                                         �
                                                                                                                                   $conditions = array(
                                                                                                                                    �          'Post.id'=>$id,
�          var $name = 'Posts';                                                                              �           �          �          'Post.user_id'=>$this->Auth->user('id'),
                                                                                                             �           �         );
�          function index() {                                                                                �           �         $post = $this->Post->find('first', compact('conditions'));
�          �          $this->paginate = array(                                                               �           �         if (!$post) {
�          �          �         'conditions'=>array(                                                         �           �          �          $this->Session->setFlash(__('Invalid Post', true));
�          �          �         �           'Post.user_id'=>$this->Auth->user('id'),                         �           �          �          $this->redirect(array('action'=>'index'));
�          �          �         ),                                                                           �           �         }
�          �          );                                                                                     �           �         if (!empty($this->data)) {
�          �          $this->Post->recursive = 0;                                                            �           �          �          if (!$this->data['Post']['image']['error']) {
�          �          $this->set('posts', $this->paginate());                                                �           �          �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�          }                                                                                                 �           �          �          �           move_uploaded_file(
                                                                                                             �           �          �          �           �         $this->data['Post']['image']['tmp_name'],
�          function view($id = null) {                                                                       �           �          �          �           �         WWW_ROOT.'img'.DS.$filename);
�          �          $conditions = array(                                                                   �           �          �          �           $this->data['Post']['image'] = $filename;
�          �          �           'Post.id'=>$id,                                                            �           �          �          } else {
�          �          �           'Post.user_id'=>$this->Auth->user('id'),                                   �           �          �          �           unset($this->data['Post']['image']);
�          �          );                                                                                     �           �          �          }
�          �          $post = $this->Post->find('first', compact('conditions'));                             �           �          �          if ($this->Post->save($this->data)) {
�          �          if (!$post) {                                                                          �           �          �          �           $this->Session->setFlash(__('The Post has been saved', true));
�          �          �           $this->Session->setFlash(__('Invalid Post.', true));                       �           �          �          �           $this->redirect(array('action'=>'index'));
�          �          �           $this->redirect(array('action'=>'index'));                                 �           �          �          } else {
�          �          }                                                                                      �           �          �          �           $this->Session->setFlash(__('The Post could not be saved. Please, try
�          �          $this->set(compact('post'));                                                           again.', true));
�          }                                                                                                 �           �          �          }
                                                                                                             �           �         } else {
�          function add() {                                                                                  �           �          �          $this->data = $post;
�           �           if (!empty($this->data)) {                                                           �           �         }
�           �           �          if (!$this->data['Post']['image']['error']) {                             �           }
�           �           �          �           $filename = 'post'.DS.$this->data['Post']['image']['name'];
�           �           �          �           move_uploaded_file(                                           �         function delete($id = null) {
�           �           �          �           �         $this->data['Post']['image']['tmp_name'],           �         �         $conditions = array(
�           �           �          �           �         WWW_ROOT.'img'.DS.$filename);                       �         �          �          'Post.id'=>$id,
�           �           �          �           $this->data['Post']['image'] = $filename;                     �         �          �          'Post.user_id'=>$this->Auth->user('id'),
�           �           �          } else {                                                                  �         �         );
�           �           �          �           unset($this->data['Post']['image']);                          �         �         $post = $this->Post->find('first', compact('conditions'));
�           �           �          }                                                                         �         �         if (!$post) {
�           �           �          $this->data['Post']['user_id'] = $this->Auth->user('id');                 �         �          �          $this->Session->setFlash(__('Invalid id for Post', true));
�           �           �          $this->Post->create();                                                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          if ($this->Post->save($this->data)) {                                     �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post has been saved',        �         �         if ($this->Post->del($id)) {
true));                                                                                                      �         �          �          $this->Session->setFlash(__('Post deleted', true));
�           �           �          �           $this->redirect(array('action'=>'index'));                    �         �          �          $this->redirect(array('action'=>'index'));
�           �           �          } else {                                                                  �         �         }
�           �           �          �           $this->Session->setFlash(__('The Post could not be saved.     �         }
Please, try again.', true));
�           �           �          }                                                                         }
�           �           }                                                                                    ?>
�          }
<?php
class PostsController extends AppController {

           var $name = 'Posts';


           function beforeFilter() {

           
            parent::beforeFilter();

           
            Configure::write('User.id', $this->Auth->user('id'));

           }


           function index() {

           
            $this->Post->recursive = 0;

           
            $this->set('posts', $this->paginate());

           }


           function view($id = null) {

           
            $conditions = array(

           
            
             'Post.id'=>$id,

           
            );

           
            $post = $this->Post->find('first', compact('conditions'));

           
            if (!$post) {

           
            
             $this->Session->setFlash(__('Invalid Post.', true));

           
            
             $this->redirect(array('action'=>'index'));

           
            }

           
            $this->set(compact('post'));

           }


           function add() {

           
           if (!empty($this->data)) {

           
           
            $this->Post->create();

           
           
            if ($this->Post->save($this->data)) {

           
           
            
             $this->Session->setFlash(__('The Post has been saved', true));

           
           
            
             $this->redirect(array('action'=>'index'));

           
           
            } else {

           
           
            
             $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

           
           
            }

           
           }

           }


           function edit($id = null) {

           
            $conditions = array(

           
            
              'Post.id'=>$id,

           
            );

           
            $post = $this->Post->find('first', compact('conditions'));

           
            if (!$post) {

           
            
              $this->Session->setFlash(__('Invalid Post', true));

           
            
              $this->redirect(array('action'=>'index'));

           
            }

           
            if (!empty($this->data)) {

           
            
              if ($this->Post->save($this->data)) {

           
            
              
            $this->Session->setFlash(__('The Post has been saved', true));

           
            
              
            $this->redirect(array('action'=>'index'));

           
            
              } else {

           
            
              
            $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

           
            
              }

           
            } else {

           
            
              $this->data = $post;

           
            }

           }


           function delete($id = null) {

           
            $conditions = array(

           
            
             'Post.id'=>$id,

           
            );

           
            $post = $this->Post->find('first', compact('conditions'));

           
            if (!$post) {

           
            
             $this->Session->setFlash(__('Invalid id for Post', true));

           
            
             $this->redirect(array('action'=>'index'));

           
            }

           
            if ($this->Post->del($id)) {

           
            
             $this->Session->setFlash(__('Post deleted', true));

           
            
             $this->redirect(array('action'=>'index'));

           
            }

           }
}
?>
<?php
 class PostsController extends AppController {
 
           var $name = 'Posts';
 
 
           function beforeFilter() {
 
           
            parent::beforeFilter();
 
           
            Configure::write('User.id', $this->Auth->user('id'));
 
           }

 
           function index() {
 
           
            $this->Post->recursive = 0;
 
           
            $this->set('posts', $this->paginate());
 
           }

 
           function view($id = null) {
 
           
            $conditions = array(
 
           
            
             'Post.id'=>$id,
 
           
            );
 
           
            $post = $this->Post->find('first', compact('conditions'));
 
           
            if (!$post) {
 
           
            
             $this->Session->setFlash(__('Invalid Post.', true));
 
           
            
             $this->redirect(array('action'=>'index'));
 
           
            }
 
           
            $this->set(compact('post'));
 
           }

 
           function add() {
 
           
           if (!empty($this->data)) {
 
           
           
            $this->Post->create();
 
           
           
            if ($this->Post->save($this->data)) {
 
           
           
            
             $this->Session->setFlash(__('The Post has been saved', true));
 
           
           
            
             $this->redirect(array('action'=>'index'));




ふぅ…先は長い
 
           
           
            } else {
 
           
           
            
             $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));
 
           
           
            }
 
           
           }
 
           }

 
           function edit($id = null) {
 
           
            $conditions = array(
 
           
            
              'Post.id'=>$id,
 
           
            );
 
           
            $post = $this->Post->find('first', compact('conditions'));
 
           
            if (!$post) {
 
           
            
              $this->Session->setFlash(__('Invalid Post', true));
 
           
            
              $this->redirect(array('action'=>'index'));
 
           
            }
 
           
            if (!empty($this->data)) {
 
           
            
              if ($this->Post->save($this->data)) {
 
           
            
              
            $this->Session->setFlash(__('The Post has been saved', true));
 
           
            
              
            $this->redirect(array('action'=>'index'));
 
           
            
              } else {
 
           
            
              
            $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));
 
           
            
              }
 
           
            } else {
 
           
            
              $this->data = $post;
 
           
            }
 
           }

 
           function delete($id = null) {
 
           
            $conditions = array(
 
           
            
             'Post.id'=>$id,
 
           
            );
 
           
            $post = $this->Post->find('first', compact('conditions'));
 
           
            if (!$post) {
 
           
            
             $this->Session->setFlash(__('Invalid id for Post', true));
 
           
            
             $this->redirect(array('action'=>'index'));
 
           
            }
 
           
            if ($this->Post->del($id)) {
 
           
            
             $this->Session->setFlash(__('Post deleted', true));
 
           
            
             $this->redirect(array('action'=>'index'));
 
           
            }
 
           }
 }
 ?>
Component へ…
Componentに移すときの
      私的原則
フックメソッドでの処理

2つ以上のControllerで共通の処理
今回の場合は

フックメソッドでの処理

• beforeFilter()
2つ以上のControllerで共通の処理

• なし
AccountComponent

<?php
class AccountComponent extends Object {
   var $components = array('Auth');

     function startup(&$controller) {
        Configure::write('User.id', $this->Auth->user('id'));
     }
}
?>
AccountComponent
                                    startup()にて設定
<?php
class AccountComponent extends Object {
   var $components = array('Auth');

     function startup(&$controller) {
        Configure::write('User.id', $this->Auth->user('id'));
     }
}
?>
PostsController::beforeFilter()


function beforeFilter() {
  parent::beforeFilter();
  Configure::write('User.id', $this->Auth-
>user('id'));
}
PostsController::beforeFilter()


function beforeFilter() {
  parent::beforeFilter();
  Configure::write('User.id', $this->Auth-
>user('id'));
}
PostsController


<?php
class PostsController extends AppController {
  var $name = 'Posts';
  var $components = array('Account');
PostsController


<?php
class PostsController extends AppController {
  var $name = 'Posts';
  var $components = array('Account');
<?php
class PostsController extends AppController {

           var $name = 'Posts';


           function beforeFilter() {

           
            parent::beforeFilter();

           
            Configure::write('User.id', $this->Auth->user('id'));

           }


           function index() {

           
            $this->Post->recursive = 0;

           
            $this->set('posts', $this->paginate());

           }


           function view($id = null) {

           
            $conditions = array(

           
            
             'Post.id'=>$id,

           
            );

           
            $post = $this->Post->find('first', compact('conditions'));

           
            if (!$post) {

           
            
             $this->Session->setFlash(__('Invalid Post.', true));

           
            
             $this->redirect(array('action'=>'index'));

           
            }

           
            $this->set(compact('post'));

           }


           function add() {

           
           if (!empty($this->data)) {

           
           
            $this->Post->create();

           
           
            if ($this->Post->save($this->data)) {

           
           
            
             $this->Session->setFlash(__('The Post has been saved', true));

           
           
            
             $this->redirect(array('action'=>'index'));

           
           
            } else {

           
           
            
             $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

           
           
            }

           
           }

           }


           function edit($id = null) {

           
            $conditions = array(

           
            
              'Post.id'=>$id,

           
            );

           
            $post = $this->Post->find('first', compact('conditions'));

           
            if (!$post) {

           
            
              $this->Session->setFlash(__('Invalid Post', true));

           
            
              $this->redirect(array('action'=>'index'));

           
            }

           
            if (!empty($this->data)) {

           
            
              if ($this->Post->save($this->data)) {

           
            
              
            $this->Session->setFlash(__('The Post has been saved', true));

           
            
              
            $this->redirect(array('action'=>'index'));

           
            
              } else {

           
            
              
            $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

           
            
              }

           
            } else {

           
            
              $this->data = $post;

           
            }

           }


           function delete($id = null) {

           
            $conditions = array(

           
            
             'Post.id'=>$id,

           
            );

           
            $post = $this->Post->find('first', compact('conditions'));

           
            if (!$post) {

           
            
             $this->Session->setFlash(__('Invalid id for Post', true));

           
            
             $this->redirect(array('action'=>'index'));

           
            }

           
            if ($this->Post->del($id)) {

           
            
             $this->Session->setFlash(__('Post deleted', true));

           
            
             $this->redirect(array('action'=>'index'));

           
            }

           }
}
?>
<?php
class PostsController extends AppController {

           var $name = 'Posts';

           var $components = array(‘Account’);


          function index() {

          
            $this->Post->recursive = 0;

          
            $this->set('posts', $this->paginate());

          }


          function view($id = null) {

          
            $conditions = array(

          
            
             'Post.id'=>$id,

          
            );

          
            $post = $this->Post->find('first', compact('conditions'));

          
            if (!$post) {

          
            
             $this->Session->setFlash(__('Invalid Post.', true));

          
            
             $this->redirect(array('action'=>'index'));

          
            }

          
            $this->set(compact('post'));

          }


          function add() {

          
           if (!empty($this->data)) {

          
           
            $this->Post->create();

          
           
            if ($this->Post->save($this->data)) {

          
           
            
             $this->Session->setFlash(__('The Post has been saved', true));

          
           
            
             $this->redirect(array('action'=>'index'));

          
           
            } else {

          
           
            
             $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

          
           
            }

          
           }




    まだまだ…

          }


          function edit($id = null) {

          
            $conditions = array(

          
            
              'Post.id'=>$id,

          
            );

          
            $post = $this->Post->find('first', compact('conditions'));

          
            if (!$post) {

          
            
              $this->Session->setFlash(__('Invalid Post', true));

          
            
              $this->redirect(array('action'=>'index'));

          
            }

          
            if (!empty($this->data)) {

          
            
              if ($this->Post->save($this->data)) {

          
            
              
            $this->Session->setFlash(__('The Post has been saved', true));

          
            
              
            $this->redirect(array('action'=>'index'));

          
            
              } else {

          
            
              
            $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

          
            
              }

          
            } else {

          
            
              $this->data = $post;

          
            }

          }


          function delete($id = null) {

          
            $conditions = array(

          
            
             'Post.id'=>$id,

          
            );

          
            $post = $this->Post->find('first', compact('conditions'));

          
            if (!$post) {

          
            
             $this->Session->setFlash(__('Invalid id for Post', true));

          
            
             $this->redirect(array('action'=>'index'));

          
            }

          
            if ($this->Post->del($id)) {

          
            
             $this->Session->setFlash(__('Post deleted', true));

          
            
             $this->redirect(array('action'=>'index'));

          
            }

          }
}
?>
AppController へ…
AppControllerに移すときの
       私的原則

フックメソッドでの処理

2つ以上のControllerで共通の処理
今回の場合は
フックメソッドでの処理

• 既にComponentに移しているので、
 なし

2つ以上のControllerで共通の処理

• 今回の例では、Controllerが一つしか
 ないが、同様の処理(例えばリンク集
 とか)のControllerがあるとして
ポイント1
PostController

$this->Post->save()
AppController

$this->{$this->modelClass}->save()
ポイント2
 PostController
$this->set(‘posts’, $this->paginate());

 AppController
$name = Inflector::pluralize(
    Inflector::variable($this->modelClass));

$this->set($name, $this->paginate());
class Inflector
Inflector ::
実用的な各種の組み込みライブラリ ::
マニュアル :: 1.2 Collection ::
The Cookbook
 http://book.cakephp.org/ja/view/491/
Inflector
class Inflector

Inflector クラスは文字列を扱い、
複数形やキャメル記法といったように
単語のバリエーションをハンドルする
操作を行うもの
         - The Cookbook より
class Inflector




      - The Cookbook より
class Inflector
複数Controllerでの共通の処理を書く
とき、必要になるので覚えておく!
AppController::index()

function index() {
� $this->{$this->modelClass}->recursive = 0;
� $name = Inflector::pluralize(
      Inflector::variable($this->modelClass));
� $this->set($name, $this->paginate());
}
AppController::view()
function view($id = null) {
�   $conditions = array(
�   �    $this->modelClass.'.id'=>$id,
�   );
�   $data = $this->{$this->modelClass}->find(
�   �    'first', compact('conditions'));
�   if (!$data) {
�   �    $this->Session->setFlash(__('Invalid '. $this->modelClass.'.', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   $name = Inflector::singularize(
�   �    Inflector::variable($this->params['controller']));
�   $this->set($name, $data);
}
AppController::add()
function add() {
�   if (!empty($this->data)) {
�   �    $this->{$this->modelClass}->create();
�   �    if ($this->{$this->modelClass}->save($this->data)) {
�   �    �    $this->Session->setFlash(__('The '.$this->modelClass.' has been
saved', true));
�   �    �    $this->redirect(array('action'=>'index'));
�   �    } else {
�   �    �    $this->Session->setFlash(__('The '.$this->modelClass.' could not
be saved. Please, try again.', true));
�   �    }
�   }
}
AppController::edit()
function edit($id = null) {
�    $conditions = array(
�    �      $this->modelClass.'.id'=>$id,
�    );
�    $data = $this->{$this->modelClass}->find('first', compact('conditions'));
�    if (!$data) {
�    �      $this->Session->setFlash(__('Invalid '.$this->modelClass, true));
�    �      $this->redirect(array('action'=>'index'));
�    }
�    if (!empty($this->data)) {
�    �      if ($this->{$this->modelClass}->save($this->data)) {
�    �      �     $this->Session->setFlash(__('The '.$this->modelClass.' has been saved', true));
�    �      �     $this->redirect(array('action'=>'index'));
�    �      } else {
�    �      �     $this->Session->setFlash(__('The '.$this->modelClass.' could not be saved. Please, try
again.', true));
�    �      }
�    } else {
�    �      $this->data = $post;
�    }
}
AppController::delete()
function delete($id = null) {
�   $conditions = array(
�   �    $this->modelClass.'.id'=>$id,
�   );
�   $data = $this->{$this->modelClass}->find('first', compact('conditions'));
�   if (!$data) {
�   �    $this->Session->setFlash(__('Invalid id for '.$this->modelClass,
true));
�   �    $this->redirect(array('action'=>'index'));
�   }
�   if ($this->{$this->modelClass}->del($id)) {
�   �    $this->Session->setFlash(__($this->modelClass.' deleted', true));
�   �    $this->redirect(array('action'=>'index'));
�   }
}
Componentsを
      AppControllerへ
    PostController
class PostController extends AppController {

�   var $components = array('Account');

    AppController
class AppController extends Controller {

�   var $components = array('Auth', 'Account');
<?php
class PostsController extends AppController {

           var $name = 'Posts';

           var $components = array(‘Account’);


          function index() {

          
            $this->Post->recursive = 0;

          
            $this->set('posts', $this->paginate());

          }


          function view($id = null) {

          
            $conditions = array(

          
            
             'Post.id'=>$id,

          
            );

          
            $post = $this->Post->find('first', compact('conditions'));

          
            if (!$post) {

          
            
             $this->Session->setFlash(__('Invalid Post.', true));

          
            
             $this->redirect(array('action'=>'index'));

          
            }

          
            $this->set(compact('post'));

          }


          function add() {

          
           if (!empty($this->data)) {

          
           
            $this->Post->create();

          
           
            if ($this->Post->save($this->data)) {

          
           
            
             $this->Session->setFlash(__('The Post has been saved', true));

          
           
            
             $this->redirect(array('action'=>'index'));

          
           
            } else {

          
           
            
             $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

          
           
            }

          
           }

          }


          function edit($id = null) {

          
            $conditions = array(

          
            
              'Post.id'=>$id,

          
            );

          
            $post = $this->Post->find('first', compact('conditions'));

          
            if (!$post) {

          
            
              $this->Session->setFlash(__('Invalid Post', true));

          
            
              $this->redirect(array('action'=>'index'));

          
            }

          
            if (!empty($this->data)) {

          
            
              if ($this->Post->save($this->data)) {

          
            
              
            $this->Session->setFlash(__('The Post has been saved', true));

          
            
              
            $this->redirect(array('action'=>'index'));

          
            
              } else {

          
            
              
            $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true));

          
            
              }

          
            } else {

          
            
              $this->data = $post;

          
            }

          }


          function delete($id = null) {

          
            $conditions = array(

          
            
             'Post.id'=>$id,

          
            );

          
            $post = $this->Post->find('first', compact('conditions'));

          
            if (!$post) {

          
            
             $this->Session->setFlash(__('Invalid id for Post', true));

          
            
             $this->redirect(array('action'=>'index'));

          
            }

          
            if ($this->Post->del($id)) {

          
            
             $this->Session->setFlash(__('Post deleted', true));

          
            
             $this->redirect(array('action'=>'index'));

          
            }

          }
}
?>
これぞ究極!?
<?php
class PostsController extends AppController {
� var $name = 'Posts';
}
?>
おまけ
Modelのフックメソッドへ移した処理
は、そのままBehavior化できる。
UploadBehavior
class UploadBehavior extends ModelBehavior {

   function beforeSave(&$model, $options = array()) {
      if (!$model->data[$model->alias]['image']['error']) {
          $filename = low($model->alias).DS.$model-
>data[$model->alias]['image']['name'];
          move_uploaded_file(
             $model->data[$model->alias]['image']['tmp_name'],
             WWW_ROOT.'img'.DS.$filename);
          $model->data[$model->alias]['image'] = $filename;
      } else {
          unset($model->data[$model->alias]['image']);
      }
      return true;
   }
}
Post
class Post extends AppModel {
  var $name = 'Post';
  var $actsAs = array('Upload');
Post
class Post extends AppModel {
  var $name = 'Post';
  var $actsAs = array('Upload');
参考になるもの
http://thechaw.com/
参考になるもの
http://thechaw.com/cakebook
参考になるもの
http://thechaw.com/cakebook/source/
app_controller.php
参考になるもの
http://thechaw.com/cakebook/source/
app_controller.php




    AppControllerに
   共通処理をまとめてある
他にも
CakePHPを知り尽くしている人々の
コードがたくさんあるので必見!!
参考になるもの
http://bakery.cakephp.org/
参考になるもの
http://bakery.cakephp.org/articles/view/
meioupload-behavior
参考になるもの
http://bakery.cakephp.org/articles/view/
meioupload-behavior




これを見て、Upload処理は
Behaviorがいいと思った
英語だけれど…
コードが読めればOK!

怖がらずに目を通してみよう!
参考になるもの
翻訳記事
リファクタリングを考える時期の記事紹介 - cakephper
の日記
http://d.hatena.ne.jp/cakephper/
20090601/1243853035
元記事
5 signals that can indicate its time to re-
factor ¦ Mark Story
http://mark-story.com/posts/view/5-signals-
that-can-indicate-its-time-to-re-factor
リファクタリングを考える時期

メソッドのパラメータが多くなった時

ひとつのメソッドが多機能になってしまった時
同じようなコードがいくつも存在している時

名前の付け方が悪い時

あるべき場所(階層)にあるべきコードを書く
多くはメソッドについて語られているが、
  メソッドをクラスに置き換えても
      同じ事がいえる
リファクタリングを考える時期

クラスのメソッドが多くなった時

ひとつのクラスが多機能になってしまった時
同じようなコードがいくつも存在している時

名前の付け方が悪い時

あるべき場所(階層)にあるべきコードを書く
究極のコントローラを目指す
究極のコントローラを目指す

Mais conteúdo relacionado

Mais procurados

The State of Lithium
The State of LithiumThe State of Lithium
The State of LithiumNate Abele
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design PatternsHugo Hamon
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in LaravelHAO-WEN ZHANG
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of LithiumNate Abele
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistenceHugo Hamon
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011Alessandro Nadalin
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome TownRoss Tuck
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkG Woo
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Ryan Mauger
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 MinutesAzim Kurt
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHPTaras Kalapun
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsRoss Tuck
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm OldRoss Tuck
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)Night Sailer
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Editionddiers
 
Command-Oriented Architecture
Command-Oriented ArchitectureCommand-Oriented Architecture
Command-Oriented ArchitectureLuiz Messias
 

Mais procurados (20)

The State of Lithium
The State of LithiumThe State of Lithium
The State of Lithium
 
Database Design Patterns
Database Design PatternsDatabase Design Patterns
Database Design Patterns
 
Dependency Injection in Laravel
Dependency Injection in LaravelDependency Injection in Laravel
Dependency Injection in Laravel
 
The Zen of Lithium
The Zen of LithiumThe Zen of Lithium
The Zen of Lithium
 
The History of PHPersistence
The History of PHPersistenceThe History of PHPersistence
The History of PHPersistence
 
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011 Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
Be lazy, be ESI: HTTP caching and Symfony2 @ PHPDay 2011 05-13-2011
 
Command Bus To Awesome Town
Command Bus To Awesome TownCommand Bus To Awesome Town
Command Bus To Awesome Town
 
PHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php frameworkPHP 5.3 and Lithium: the most rad php framework
PHP 5.3 and Lithium: the most rad php framework
 
J slider
J sliderJ slider
J slider
 
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
Zend Framework and the Doctrine2 MongoDB ODM (ZF1)
 
50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes50 Laravel Tricks in 50 Minutes
50 Laravel Tricks in 50 Minutes
 
Separation of concerns - DPC12
Separation of concerns - DPC12Separation of concerns - DPC12
Separation of concerns - DPC12
 
Crazy things done on PHP
Crazy things done on PHPCrazy things done on PHP
Crazy things done on PHP
 
Spock and Geb
Spock and GebSpock and Geb
Spock and Geb
 
Models and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and HobgoblinsModels and Service Layers, Hemoglobin and Hobgoblins
Models and Service Layers, Hemoglobin and Hobgoblins
 
BVJS
BVJSBVJS
BVJS
 
Things I Believe Now That I'm Old
Things I Believe Now That I'm OldThings I Believe Now That I'm Old
Things I Believe Now That I'm Old
 
From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)From mysql to MongoDB(MongoDB2011北京交流会)
From mysql to MongoDB(MongoDB2011北京交流会)
 
Drupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary EditionDrupal - dbtng 25th Anniversary Edition
Drupal - dbtng 25th Anniversary Edition
 
Command-Oriented Architecture
Command-Oriented ArchitectureCommand-Oriented Architecture
Command-Oriented Architecture
 

Destaque

Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of PluginYasuo Harada
 
Chapter 2 – Near East
Chapter 2 – Near East Chapter 2 – Near East
Chapter 2 – Near East Laura Moakley
 
Babylon system found in the web
Babylon system found in the webBabylon system found in the web
Babylon system found in the webYasuo Harada
 
フレームワークの選び方・付き合い方
フレームワークの選び方・付き合い方フレームワークの選び方・付き合い方
フレームワークの選び方・付き合い方Yasuo Harada
 
PHP Conference Kansai 2015
PHP Conference Kansai 2015PHP Conference Kansai 2015
PHP Conference Kansai 2015Yasuo Harada
 

Destaque (6)

Quality Use Of Plugin
Quality Use Of PluginQuality Use Of Plugin
Quality Use Of Plugin
 
Chapter 2 – Near East
Chapter 2 – Near East Chapter 2 – Near East
Chapter 2 – Near East
 
Babylon system found in the web
Babylon system found in the webBabylon system found in the web
Babylon system found in the web
 
フレームワークの選び方・付き合い方
フレームワークの選び方・付き合い方フレームワークの選び方・付き合い方
フレームワークの選び方・付き合い方
 
Packagist
PackagistPackagist
Packagist
 
PHP Conference Kansai 2015
PHP Conference Kansai 2015PHP Conference Kansai 2015
PHP Conference Kansai 2015
 

Semelhante a 究極のコントローラを目指す

Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConRafael Dohms
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにYuya Takeyama
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix itRafael Dohms
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of TransductionDavid Stockton
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency InjectionRifat Nabi
 
CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏
CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏
CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏Masahiro Akita
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsSam Hennessy
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in actionJace Ju
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7chuvainc
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutesBarang CK
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesLuis Curo Salvatierra
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class ReferenceJamshid Hashimi
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and SanityJimKellerES
 

Semelhante a 究極のコントローラを目指す (20)

Presentation1
Presentation1Presentation1
Presentation1
 
Your code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnConYour code sucks, let's fix it - DPC UnCon
Your code sucks, let's fix it - DPC UnCon
 
PHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くためにPHPUnit でよりよくテストを書くために
PHPUnit でよりよくテストを書くために
 
You code sucks, let's fix it
You code sucks, let's fix itYou code sucks, let's fix it
You code sucks, let's fix it
 
The Art of Transduction
The Art of TransductionThe Art of Transduction
The Art of Transduction
 
Dependency Injection
Dependency InjectionDependency Injection
Dependency Injection
 
Bacbkone js
Bacbkone jsBacbkone js
Bacbkone js
 
CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏
CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏
CakePHPをさらにDRYにする、ドライケーキレシピ akiyan.com 秋田真宏
 
Adding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy ApplicationsAdding Dependency Injection to Legacy Applications
Adding Dependency Injection to Legacy Applications
 
Advanced php testing in action
Advanced php testing in actionAdvanced php testing in action
Advanced php testing in action
 
DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7DrupalCamp Foz - Novas APIs Drupal 7
DrupalCamp Foz - Novas APIs Drupal 7
 
laravel tricks in 50minutes
laravel tricks in 50minuteslaravel tricks in 50minutes
laravel tricks in 50minutes
 
Desarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móvilesDesarrollo de módulos en Drupal e integración con dispositivos móviles
Desarrollo de módulos en Drupal e integración con dispositivos móviles
 
CodeIgniter Class Reference
CodeIgniter Class ReferenceCodeIgniter Class Reference
CodeIgniter Class Reference
 
Lithium Best
Lithium Best Lithium Best
Lithium Best
 
Oops in php
Oops in phpOops in php
Oops in php
 
Coding for Scale and Sanity
Coding for Scale and SanityCoding for Scale and Sanity
Coding for Scale and Sanity
 
画像Hacks
画像Hacks画像Hacks
画像Hacks
 
Min-Maxing Software Costs
Min-Maxing Software CostsMin-Maxing Software Costs
Min-Maxing Software Costs
 
Intermediate PHP
Intermediate PHPIntermediate PHP
Intermediate PHP
 

Último

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Alkin Tezuysal
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterMydbops
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfIngrid Airi González
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality AssuranceInflectra
 

Último (20)

Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data PrivacyTrustArc Webinar - How to Build Consumer Trust Through Data Privacy
TrustArc Webinar - How to Build Consumer Trust Through Data Privacy
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
Unleashing Real-time Insights with ClickHouse_ Navigating the Landscape in 20...
 
Scale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL RouterScale your database traffic with Read & Write split using MySQL Router
Scale your database traffic with Read & Write split using MySQL Router
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Generative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdfGenerative Artificial Intelligence: How generative AI works.pdf
Generative Artificial Intelligence: How generative AI works.pdf
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance[Webinar] SpiraTest - Setting New Standards in Quality Assurance
[Webinar] SpiraTest - Setting New Standards in Quality Assurance
 

究極のコントローラを目指す

  • 2. 自己紹介 原田 康生 Yasuo Harada 大阪のこっそりPHPer 忍び歩く男 - SLYWALKER http://d.hatena.ne.jp/slywalker/ Twitter, Wassr, Hatena, GitHub ID slywalker
  • 3. 自己紹介 原田 康生 Yasuo Harada 大阪のこっそりPHPer 忍び歩く男 - SLYWALKER http://d.hatena.ne.jp/slywalker/ Twitter, Wassr, Hatena, GitHub ID slywalker
  • 11. <?php � function edit($id = null) { class PostsController extends AppController { � � � � $conditions = array( � 'Post.id'=>$id, � var $name = 'Posts'; � � � 'Post.user_id'=>$this->Auth->user('id'), � � ); � function index() { � � $post = $this->Post->find('first', compact('conditions')); � � $this->paginate = array( � � if (!$post) { � � � 'conditions'=>array( � � � $this->Session->setFlash(__('Invalid Post', true)); � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � $this->redirect(array('action'=>'index')); � � � ), � � } � � ); � � if (!empty($this->data)) { � � $this->Post->recursive = 0; � � � if (!$this->data['Post']['image']['error']) { � � $this->set('posts', $this->paginate()); � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � } � � � � move_uploaded_file( � � � � � $this->data['Post']['image']['tmp_name'], � function view($id = null) { � � � � � WWW_ROOT.'img'.DS.$filename); � � $conditions = array( � � � � $this->data['Post']['image'] = $filename; � � � 'Post.id'=>$id, � � � } else { � � � 'Post.user_id'=>$this->Auth->user('id'), � � � � unset($this->data['Post']['image']); � � ); � � � } � � $post = $this->Post->find('first', compact('conditions')); � � � if ($this->Post->save($this->data)) { � � if (!$post) { � � � � $this->Session->setFlash(__('The Post has been saved', true)); � � � $this->Session->setFlash(__('Invalid Post.', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. Please, try � � $this->set(compact('post')); again.', true)); � } � � � } � � } else { � function add() { � � � $this->data = $post; � � if (!empty($this->data)) { � � } � � � if (!$this->data['Post']['image']['error']) { � } � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � � move_uploaded_file( � function delete($id = null) { � � � � � $this->data['Post']['image']['tmp_name'], � � $conditions = array( � � � � � WWW_ROOT.'img'.DS.$filename); � � � 'Post.id'=>$id, � � � � $this->data['Post']['image'] = $filename; � � � 'Post.user_id'=>$this->Auth->user('id'), � � � } else { � � ); � � � � unset($this->data['Post']['image']); � � $post = $this->Post->find('first', compact('conditions')); � � � } � � if (!$post) { � � � $this->data['Post']['user_id'] = $this->Auth->user('id'); � � � $this->Session->setFlash(__('Invalid id for Post', true)); � � � $this->Post->create(); � � � $this->redirect(array('action'=>'index')); � � � if ($this->Post->save($this->data)) { � � } � � � � $this->Session->setFlash(__('The Post has been saved', � � if ($this->Post->del($id)) { true)); � � � $this->Session->setFlash(__('Post deleted', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. � } Please, try again.', true)); � � � } } � � } ?> � }
  • 12. <?php � function edit($id = null) { class PostsController extends AppController { � � � � $conditions = array( � 'Post.id'=>$id, � var $name = 'Posts'; � � � 'Post.user_id'=>$this->Auth->user('id'), � � ); � function index() { � � $post = $this->Post->find('first', compact('conditions')); � � $this->paginate = array( � � if (!$post) { � � � 'conditions'=>array( � � � $this->Session->setFlash(__('Invalid Post', true)); � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � $this->redirect(array('action'=>'index')); � � � ), � � } � � ); � � if (!empty($this->data)) { � � $this->Post->recursive = 0; � � � if (!$this->data['Post']['image']['error']) { � � $this->set('posts', $this->paginate()); � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � } � � � � move_uploaded_file( � � � � � $this->data['Post']['image']['tmp_name'], � function view($id = null) { � � � � � WWW_ROOT.'img'.DS.$filename); � � $conditions = array( � � � � $this->data['Post']['image'] = $filename; � � � 'Post.id'=>$id, � � � } else { � � � 'Post.user_id'=>$this->Auth->user('id'), � � � � unset($this->data['Post']['image']); � � ); � � � } � � $post = $this->Post->find('first', compact('conditions')); � � � if ($this->Post->save($this->data)) { � � if (!$post) { � � � � $this->Session->setFlash(__('The Post has been saved', true)); このControllerが � � � $this->Session->setFlash(__('Invalid Post.', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. Please, try � � $this->set(compact('post')); again.', true)); � } � � � } � � } else { � function add() { � � � $this->data = $post; � � if (!empty($this->data)) { � � } � � � if (!$this->data['Post']['image']['error']) { � } � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � � move_uploaded_file( � function delete($id = null) { � � � � � $this->data['Post']['image']['tmp_name'], � � $conditions = array( � � � � � WWW_ROOT.'img'.DS.$filename); � � � 'Post.id'=>$id, � � � � $this->data['Post']['image'] = $filename; � � � 'Post.user_id'=>$this->Auth->user('id'), � � � } else { � � ); � � � � unset($this->data['Post']['image']); � � $post = $this->Post->find('first', compact('conditions')); � � � } � � if (!$post) { � � � $this->data['Post']['user_id'] = $this->Auth->user('id'); � � � $this->Session->setFlash(__('Invalid id for Post', true)); � � � $this->Post->create(); � � � $this->redirect(array('action'=>'index')); � � � if ($this->Post->save($this->data)) { � � } � � � � $this->Session->setFlash(__('The Post has been saved', � � if ($this->Post->del($id)) { true)); � � � $this->Session->setFlash(__('Post deleted', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. � } Please, try again.', true)); � � � } } � � } ?> � }
  • 13. <?php class PostsController extends AppController { � var $name = 'Posts'; } ?>
  • 14. こうなるまでの <?php class PostsController extends AppController { � var $name = 'Posts'; } ?>
  • 15. こうなるまでの <?php class PostsController extends AppController { � var $name = 'Posts'; } ?> 実録公開
  • 19. ※注意 • あくまでもリファクタリングの例です。 • 必ずしもここまでやれ! といったものではありません。 • 用法、用量を守り 正しくお使いください。
  • 20. <?php � function edit($id = null) { class PostsController extends AppController { � � � � $conditions = array( � 'Post.id'=>$id, � var $name = 'Posts'; � � � 'Post.user_id'=>$this->Auth->user('id'), � � ); � function index() { � � $post = $this->Post->find('first', compact('conditions')); � � $this->paginate = array( � � if (!$post) { � � � 'conditions'=>array( � � � $this->Session->setFlash(__('Invalid Post', true)); � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � $this->redirect(array('action'=>'index')); � � � ), � � } � � ); � � if (!empty($this->data)) { � � $this->Post->recursive = 0; � � � if (!$this->data['Post']['image']['error']) { � � $this->set('posts', $this->paginate()); � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � } � � � � move_uploaded_file( � � � � � $this->data['Post']['image']['tmp_name'], � function view($id = null) { � � � � � WWW_ROOT.'img'.DS.$filename); � � $conditions = array( � � � � $this->data['Post']['image'] = $filename; � � � 'Post.id'=>$id, � � � } else { � � � 'Post.user_id'=>$this->Auth->user('id'), � � � � unset($this->data['Post']['image']); � � ); � � � } � � $post = $this->Post->find('first', compact('conditions')); � � � if ($this->Post->save($this->data)) { � � if (!$post) { � � � � $this->Session->setFlash(__('The Post has been saved', true)); � � � $this->Session->setFlash(__('Invalid Post.', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. Please, try � � $this->set(compact('post')); again.', true)); � } � � � } � � } else { � function add() { � � � $this->data = $post; � � if (!empty($this->data)) { � � } � � � if (!$this->data['Post']['image']['error']) { � } � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � � move_uploaded_file( � function delete($id = null) { � � � � � $this->data['Post']['image']['tmp_name'], � � $conditions = array( � � � � � WWW_ROOT.'img'.DS.$filename); � � � 'Post.id'=>$id, � � � � $this->data['Post']['image'] = $filename; � � � 'Post.user_id'=>$this->Auth->user('id'), � � � } else { � � ); � � � � unset($this->data['Post']['image']); � � $post = $this->Post->find('first', compact('conditions')); � � � } � � if (!$post) { � � � $this->data['Post']['user_id'] = $this->Auth->user('id'); � � � $this->Session->setFlash(__('Invalid id for Post', true)); � � � $this->Post->create(); � � � $this->redirect(array('action'=>'index')); � � � if ($this->Post->save($this->data)) { � � } � � � � $this->Session->setFlash(__('The Post has been saved', � � if ($this->Post->del($id)) { true)); � � � $this->Session->setFlash(__('Post deleted', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. � } Please, try again.', true)); � � � } } � � } ?> � }
  • 21. <?php � function edit($id = null) { class PostsController extends AppController { � � � � $conditions = array( � 'Post.id'=>$id, � var $name = 'Posts'; � � � 'Post.user_id'=>$this->Auth->user('id'), � � ); � function index() { � � $post = $this->Post->find('first', compact('conditions')); � � $this->paginate = array( � � if (!$post) { � � � 'conditions'=>array( � � � $this->Session->setFlash(__('Invalid Post', true)); � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � $this->redirect(array('action'=>'index')); � � � ), � � } � � ); � � if (!empty($this->data)) { � � $this->Post->recursive = 0; � � � if (!$this->data['Post']['image']['error']) { � � $this->set('posts', $this->paginate()); � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; さて、 � } � � � � move_uploaded_file( � � � � � $this->data['Post']['image']['tmp_name'], � function view($id = null) { � � � � � WWW_ROOT.'img'.DS.$filename); � � $conditions = array( � � � � $this->data['Post']['image'] = $filename; � � � 'Post.id'=>$id, � � � } else { � � � 'Post.user_id'=>$this->Auth->user('id'), � � � � unset($this->data['Post']['image']); � � ); � � � } � � $post = $this->Post->find('first', compact('conditions')); � � � if ($this->Post->save($this->data)) { � � if (!$post) { � � � � $this->Session->setFlash(__('The Post has been saved', true)); � � � $this->Session->setFlash(__('Invalid Post.', true)); � � � � $this->redirect(array('action'=>'index')); Bad cake の中身を � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. Please, try � � $this->set(compact('post')); again.', true)); � } � � � } � � } else { � function add() { � � � $this->data = $post; � � if (!empty($this->data)) { � � } � � � if (!$this->data['Post']['image']['error']) { � } � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � � move_uploaded_file( 見てみる � function delete($id = null) { � � � � � $this->data['Post']['image']['tmp_name'], � � $conditions = array( � � � � � WWW_ROOT.'img'.DS.$filename); � � � 'Post.id'=>$id, � � � � $this->data['Post']['image'] = $filename; � � � 'Post.user_id'=>$this->Auth->user('id'), � � � } else { � � ); � � � � unset($this->data['Post']['image']); � � $post = $this->Post->find('first', compact('conditions')); � � � } � � if (!$post) { � � � $this->data['Post']['user_id'] = $this->Auth->user('id'); � � � $this->Session->setFlash(__('Invalid id for Post', true)); � � � $this->Post->create(); � � � $this->redirect(array('action'=>'index')); � � � if ($this->Post->save($this->data)) { � � } � � � � $this->Session->setFlash(__('The Post has been saved', � � if ($this->Post->del($id)) { true)); � � � $this->Session->setFlash(__('Post deleted', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. � } Please, try again.', true)); � � � } } � � } ?> � }
  • 22. PostsController::index() � function index() { � � $this->paginate = array( � � � 'conditions'=>array( � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � ), � � ); � � $this->Post->recursive = 0; � � $this->set('posts', $this->paginate()); � }
  • 23. PostsController::index() � function index() { user_idで絞り込み � � $this->paginate = array( � � � 'conditions'=>array( � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � ), � � ); � � $this->Post->recursive = 0; � � $this->set('posts', $this->paginate()); � }
  • 24. PostsController::view() function view($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post.', true)); � � $this->redirect(array('action'=>'index')); � } � $this->set(compact('post')); }
  • 25. PostsController::view() user_idで絞り込み function view($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post.', true)); � � $this->redirect(array('action'=>'index')); � } � $this->set(compact('post')); }
  • 26. PostsController::add() function add() { � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � � $this->data['Post']['user_id'] = $this->Auth->user('id');
  • 27. PostsController::add() function add() { FileUpload処理 � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � � $this->data['Post']['user_id'] = $this->Auth->user('id');
  • 28. PostsController::add() function add() { FileUpload処理 � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � � $this->data['Post']['user_id'] = $this->Auth->user('id'); user_idの付与
  • 29. PostsController::add() � � $this->Post->create(); � � if ($this->Post->save($this->data)) { � � � $this->Session->setFlash(__('The Post has been saved', true)); � � � $this->redirect(array('action'=>'index')); � � } else { � � � $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); � � } � } }
  • 30. PostsController::edit() function edit($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post', true)); � � $this->redirect(array('action'=>'index')); � }
  • 31. PostsController::edit() user_idで絞り込み function edit($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post', true)); � � $this->redirect(array('action'=>'index')); � }
  • 32. PostsController::edit() � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � }
  • 33. PostsController::edit() FileUpload処理 � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � }
  • 34. PostsController::edit() � � if ($this->Post->save($this->data)) { � � � $this->Session->setFlash(__('The Post has been saved', true)); � � � $this->redirect(array('action'=>'index')); � � } else { � � � $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); � � } � } else { � � $this->data = $post; � } }
  • 35. PostsController::delete() function delete($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid id for Post', true)); � � $this->redirect(array('action'=>'index')); � } � if ($this->Post->del($id)) { � � $this->Session->setFlash(__('Post deleted', true)); � � $this->redirect(array('action'=>'index')); � } }
  • 36. PostsController::delete() function delete($id = null) { user_idで絞り込み � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid id for Post', true)); � � $this->redirect(array('action'=>'index')); � } � if ($this->Post->del($id)) { � � $this->Session->setFlash(__('Post deleted', true)); � � $this->redirect(array('action'=>'index')); � } }
  • 37.
  • 39. Modelに移すときの 私的原則 各メソッドで共通の検索条件 $this->data の繰作
  • 42. PostsController::beforeFilter() function beforeFilter() { � parent::beforeFilter(); � Configure::write('User.id', $this->Auth->user('id')); }
  • 43. PostsController::beforeFilter() user_idを書き込み function beforeFilter() { � parent::beforeFilter(); � Configure::write('User.id', $this->Auth->user('id')); }
  • 44. Post::beforeFind() function beforeFind($queryData) { � $conditions = array( � � $this->alias.'.user_id'=>Configure::read('User.id'), � ); � $queryData['conditions'] = � Set::merge($queryData['conditions'], $conditions); � return $queryData; }
  • 45. Post::beforeFind() user_idを読み出し function beforeFind($queryData) { � $conditions = array( � � $this->alias.'.user_id'=>Configure::read('User.id'), � ); � $queryData['conditions'] = � Set::merge($queryData['conditions'], $conditions); � return $queryData; }
  • 46. Post::beforeFind() user_idを読み出し function beforeFind($queryData) { � $conditions = array( � � $this->alias.'.user_id'=>Configure::read('User.id'), � ); � $queryData['conditions'] = � Set::merge($queryData['conditions'], $conditions); � return $queryData; } conditionsは多次元配列になりえる ので、Set::merge()を使う
  • 47. PostsController::index() � function index() { � � $this->paginate = array( � � � 'conditions'=>array( � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � ), � � ); � � $this->Post->recursive = 0; � � $this->set('posts', $this->paginate()); � }
  • 48. PostsController::index() � function index() { � � $this->paginate = array( � � � 'conditions'=>array( � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � ), � � ); � � $this->Post->recursive = 0; � � $this->set('posts', $this->paginate()); � }
  • 49. PostsController::index() � function index() { � � $this->paginate = array( � � � 'conditions'=>array( � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � ), � � ); � � $this->Post->recursive = 0; � � $this->set('posts', $this->paginate()); � }
  • 50. PostsController::view() function view($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post.', true)); � � $this->redirect(array('action'=>'index')); � } � $this->set(compact('post')); }
  • 51. PostsController::view() function view($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post.', true)); � � $this->redirect(array('action'=>'index')); � } � $this->set(compact('post')); }
  • 52. PostsController::view() function view($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post.', true)); � � $this->redirect(array('action'=>'index')); � } � $this->set(compact('post')); }
  • 53. PostsController::edit() function edit($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post', true)); � � $this->redirect(array('action'=>'index')); � }
  • 54. PostsController::edit() function edit($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post', true)); � � $this->redirect(array('action'=>'index')); � }
  • 55. PostsController::edit() function edit($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid Post', true)); � � $this->redirect(array('action'=>'index')); � }
  • 56. PostsController::delete() function delete($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid id for Post', true)); � � $this->redirect(array('action'=>'index')); � } � if ($this->Post->del($id)) { � � $this->Session->setFlash(__('Post deleted', true)); � � $this->redirect(array('action'=>'index')); � } }
  • 57. PostsController::delete() function delete($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid id for Post', true)); � � $this->redirect(array('action'=>'index')); � } � if ($this->Post->del($id)) { � � $this->Session->setFlash(__('Post deleted', true)); � � $this->redirect(array('action'=>'index')); � } }
  • 58. PostsController::delete() function delete($id = null) { � $conditions = array( � � 'Post.id'=>$id, � � 'Post.user_id'=>$this->Auth->user('id'), � ); � $post = $this->Post->find('first', compact('conditions')); � if (!$post) { � � $this->Session->setFlash(__('Invalid id for Post', true)); � � $this->redirect(array('action'=>'index')); � } � if ($this->Post->del($id)) { � � $this->Session->setFlash(__('Post deleted', true)); � � $this->redirect(array('action'=>'index')); � } }
  • 60. Post::beforeValidate() function beforeValidate($options = array()) { � $this->data[$this->alias]['user_id'] = Configure::read('User.id'); � return true; }
  • 61. Post::beforeValidate() user_idを読み出し function beforeValidate($options = array()) { � $this->data[$this->alias]['user_id'] = Configure::read('User.id'); � return true; }
  • 62. PostsController::add() function add() { � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � � $this->data['Post']['user_id'] = $this->Auth->user('id');
  • 63. PostsController::add() function add() { � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � � $this->data['Post']['user_id'] = $this->Auth->user('id');
  • 64. PostsController::add() function add() { � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � � $this->data['Post']['user_id'] = $this->Auth->user('id');
  • 66. Post::beforeSave() function beforeSave($options = array()) { � if (!$this->data[$this->alias]['image']['error']) { � � $filename = � � low($this->alias).DS.$this->data[$this->alias]['image']['name']; � � move_uploaded_file( � � � $this->data[$this->alias]['image']['tmp_name'], � � � WWW_ROOT.'img'.DS.$filename); � � $this->data[$this->alias]['image'] = $filename; � } else { � � unset($this->data[$this->alias]['image']); � }� � return true; }
  • 67. Post::beforeSave() FileUpload処理 function beforeSave($options = array()) { � if (!$this->data[$this->alias]['image']['error']) { � � $filename = � � low($this->alias).DS.$this->data[$this->alias]['image']['name']; � � move_uploaded_file( � � � $this->data[$this->alias]['image']['tmp_name'], � � � WWW_ROOT.'img'.DS.$filename); � � $this->data[$this->alias]['image'] = $filename; � } else { � � unset($this->data[$this->alias]['image']); � }� � return true; }
  • 68. PostsController::add() function add() { � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � �
  • 69. PostsController::add() function add() { � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � �
  • 70. PostsController::add() function add() { � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � } � �
  • 71. PostsController::edit() � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � }
  • 72. PostsController::edit() � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � }
  • 73. PostsController::edit() � if (!empty($this->data)) { � � if (!$this->data['Post']['image']['error']) { � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � move_uploaded_file( � � � � $this->data['Post']['image']['tmp_name'], � � � � WWW_ROOT.'img'.DS.$filename); � � � $this->data['Post']['image'] = $filename; � � } else { � � � unset($this->data['Post']['image']); � � }
  • 74. <?php � function edit($id = null) { class PostsController extends AppController { � � � � $conditions = array( � 'Post.id'=>$id, � var $name = 'Posts'; � � � 'Post.user_id'=>$this->Auth->user('id'), � � ); � function index() { � � $post = $this->Post->find('first', compact('conditions')); � � $this->paginate = array( � � if (!$post) { � � � 'conditions'=>array( � � � $this->Session->setFlash(__('Invalid Post', true)); � � � � 'Post.user_id'=>$this->Auth->user('id'), � � � $this->redirect(array('action'=>'index')); � � � ), � � } � � ); � � if (!empty($this->data)) { � � $this->Post->recursive = 0; � � � if (!$this->data['Post']['image']['error']) { � � $this->set('posts', $this->paginate()); � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � } � � � � move_uploaded_file( � � � � � $this->data['Post']['image']['tmp_name'], � function view($id = null) { � � � � � WWW_ROOT.'img'.DS.$filename); � � $conditions = array( � � � � $this->data['Post']['image'] = $filename; � � � 'Post.id'=>$id, � � � } else { � � � 'Post.user_id'=>$this->Auth->user('id'), � � � � unset($this->data['Post']['image']); � � ); � � � } � � $post = $this->Post->find('first', compact('conditions')); � � � if ($this->Post->save($this->data)) { � � if (!$post) { � � � � $this->Session->setFlash(__('The Post has been saved', true)); � � � $this->Session->setFlash(__('Invalid Post.', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. Please, try � � $this->set(compact('post')); again.', true)); � } � � � } � � } else { � function add() { � � � $this->data = $post; � � if (!empty($this->data)) { � � } � � � if (!$this->data['Post']['image']['error']) { � } � � � � $filename = 'post'.DS.$this->data['Post']['image']['name']; � � � � move_uploaded_file( � function delete($id = null) { � � � � � $this->data['Post']['image']['tmp_name'], � � $conditions = array( � � � � � WWW_ROOT.'img'.DS.$filename); � � � 'Post.id'=>$id, � � � � $this->data['Post']['image'] = $filename; � � � 'Post.user_id'=>$this->Auth->user('id'), � � � } else { � � ); � � � � unset($this->data['Post']['image']); � � $post = $this->Post->find('first', compact('conditions')); � � � } � � if (!$post) { � � � $this->data['Post']['user_id'] = $this->Auth->user('id'); � � � $this->Session->setFlash(__('Invalid id for Post', true)); � � � $this->Post->create(); � � � $this->redirect(array('action'=>'index')); � � � if ($this->Post->save($this->data)) { � � } � � � � $this->Session->setFlash(__('The Post has been saved', � � if ($this->Post->del($id)) { true)); � � � $this->Session->setFlash(__('Post deleted', true)); � � � � $this->redirect(array('action'=>'index')); � � � $this->redirect(array('action'=>'index')); � � � } else { � � } � � � � $this->Session->setFlash(__('The Post could not be saved. � } Please, try again.', true)); � � � } } � � } ?> � }
  • 75. <?php class PostsController extends AppController { var $name = 'Posts'; function beforeFilter() { parent::beforeFilter(); Configure::write('User.id', $this->Auth->user('id')); } function index() { $this->Post->recursive = 0; $this->set('posts', $this->paginate()); } function view($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post.', true)); $this->redirect(array('action'=>'index')); } $this->set(compact('post')); } function add() { if (!empty($this->data)) { $this->Post->create(); if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } } function edit($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post', true)); $this->redirect(array('action'=>'index')); } if (!empty($this->data)) { if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } else { $this->data = $post; } } function delete($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid id for Post', true)); $this->redirect(array('action'=>'index')); } if ($this->Post->del($id)) { $this->Session->setFlash(__('Post deleted', true)); $this->redirect(array('action'=>'index')); } } } ?>
  • 76. <?php class PostsController extends AppController { var $name = 'Posts'; function beforeFilter() { parent::beforeFilter(); Configure::write('User.id', $this->Auth->user('id')); } function index() { $this->Post->recursive = 0; $this->set('posts', $this->paginate()); } function view($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post.', true)); $this->redirect(array('action'=>'index')); } $this->set(compact('post')); } function add() { if (!empty($this->data)) { $this->Post->create(); if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); ふぅ…先は長い } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } } function edit($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post', true)); $this->redirect(array('action'=>'index')); } if (!empty($this->data)) { if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } else { $this->data = $post; } } function delete($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid id for Post', true)); $this->redirect(array('action'=>'index')); } if ($this->Post->del($id)) { $this->Session->setFlash(__('Post deleted', true)); $this->redirect(array('action'=>'index')); } } } ?>
  • 77.
  • 79. Componentに移すときの 私的原則 フックメソッドでの処理 2つ以上のControllerで共通の処理
  • 81. AccountComponent <?php class AccountComponent extends Object { var $components = array('Auth'); function startup(&$controller) { Configure::write('User.id', $this->Auth->user('id')); } } ?>
  • 82. AccountComponent startup()にて設定 <?php class AccountComponent extends Object { var $components = array('Auth'); function startup(&$controller) { Configure::write('User.id', $this->Auth->user('id')); } } ?>
  • 83. PostsController::beforeFilter() function beforeFilter() { parent::beforeFilter(); Configure::write('User.id', $this->Auth- >user('id')); }
  • 84. PostsController::beforeFilter() function beforeFilter() { parent::beforeFilter(); Configure::write('User.id', $this->Auth- >user('id')); }
  • 85. PostsController <?php class PostsController extends AppController { var $name = 'Posts'; var $components = array('Account');
  • 86. PostsController <?php class PostsController extends AppController { var $name = 'Posts'; var $components = array('Account');
  • 87. <?php class PostsController extends AppController { var $name = 'Posts'; function beforeFilter() { parent::beforeFilter(); Configure::write('User.id', $this->Auth->user('id')); } function index() { $this->Post->recursive = 0; $this->set('posts', $this->paginate()); } function view($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post.', true)); $this->redirect(array('action'=>'index')); } $this->set(compact('post')); } function add() { if (!empty($this->data)) { $this->Post->create(); if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } } function edit($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post', true)); $this->redirect(array('action'=>'index')); } if (!empty($this->data)) { if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } else { $this->data = $post; } } function delete($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid id for Post', true)); $this->redirect(array('action'=>'index')); } if ($this->Post->del($id)) { $this->Session->setFlash(__('Post deleted', true)); $this->redirect(array('action'=>'index')); } } } ?>
  • 88. <?php class PostsController extends AppController { var $name = 'Posts'; var $components = array(‘Account’); function index() { $this->Post->recursive = 0; $this->set('posts', $this->paginate()); } function view($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post.', true)); $this->redirect(array('action'=>'index')); } $this->set(compact('post')); } function add() { if (!empty($this->data)) { $this->Post->create(); if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } まだまだ… } function edit($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post', true)); $this->redirect(array('action'=>'index')); } if (!empty($this->data)) { if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } else { $this->data = $post; } } function delete($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid id for Post', true)); $this->redirect(array('action'=>'index')); } if ($this->Post->del($id)) { $this->Session->setFlash(__('Post deleted', true)); $this->redirect(array('action'=>'index')); } } } ?>
  • 89.
  • 91. AppControllerに移すときの 私的原則 フックメソッドでの処理 2つ以上のControllerで共通の処理
  • 92. 今回の場合は フックメソッドでの処理 • 既にComponentに移しているので、 なし 2つ以上のControllerで共通の処理 • 今回の例では、Controllerが一つしか ないが、同様の処理(例えばリンク集 とか)のControllerがあるとして
  • 94. ポイント2 PostController $this->set(‘posts’, $this->paginate()); AppController $name = Inflector::pluralize( Inflector::variable($this->modelClass)); $this->set($name, $this->paginate());
  • 95. class Inflector Inflector :: 実用的な各種の組み込みライブラリ :: マニュアル :: 1.2 Collection :: The Cookbook http://book.cakephp.org/ja/view/491/ Inflector
  • 97. class Inflector - The Cookbook より
  • 99. AppController::index() function index() { � $this->{$this->modelClass}->recursive = 0; � $name = Inflector::pluralize( Inflector::variable($this->modelClass)); � $this->set($name, $this->paginate()); }
  • 100. AppController::view() function view($id = null) { � $conditions = array( � � $this->modelClass.'.id'=>$id, � ); � $data = $this->{$this->modelClass}->find( � � 'first', compact('conditions')); � if (!$data) { � � $this->Session->setFlash(__('Invalid '. $this->modelClass.'.', true)); � � $this->redirect(array('action'=>'index')); � } � $name = Inflector::singularize( � � Inflector::variable($this->params['controller'])); � $this->set($name, $data); }
  • 101. AppController::add() function add() { � if (!empty($this->data)) { � � $this->{$this->modelClass}->create(); � � if ($this->{$this->modelClass}->save($this->data)) { � � � $this->Session->setFlash(__('The '.$this->modelClass.' has been saved', true)); � � � $this->redirect(array('action'=>'index')); � � } else { � � � $this->Session->setFlash(__('The '.$this->modelClass.' could not be saved. Please, try again.', true)); � � } � } }
  • 102. AppController::edit() function edit($id = null) { � $conditions = array( � � $this->modelClass.'.id'=>$id, � ); � $data = $this->{$this->modelClass}->find('first', compact('conditions')); � if (!$data) { � � $this->Session->setFlash(__('Invalid '.$this->modelClass, true)); � � $this->redirect(array('action'=>'index')); � } � if (!empty($this->data)) { � � if ($this->{$this->modelClass}->save($this->data)) { � � � $this->Session->setFlash(__('The '.$this->modelClass.' has been saved', true)); � � � $this->redirect(array('action'=>'index')); � � } else { � � � $this->Session->setFlash(__('The '.$this->modelClass.' could not be saved. Please, try again.', true)); � � } � } else { � � $this->data = $post; � } }
  • 103. AppController::delete() function delete($id = null) { � $conditions = array( � � $this->modelClass.'.id'=>$id, � ); � $data = $this->{$this->modelClass}->find('first', compact('conditions')); � if (!$data) { � � $this->Session->setFlash(__('Invalid id for '.$this->modelClass, true)); � � $this->redirect(array('action'=>'index')); � } � if ($this->{$this->modelClass}->del($id)) { � � $this->Session->setFlash(__($this->modelClass.' deleted', true)); � � $this->redirect(array('action'=>'index')); � } }
  • 104. Componentsを AppControllerへ PostController class PostController extends AppController { � var $components = array('Account'); AppController class AppController extends Controller { � var $components = array('Auth', 'Account');
  • 105. <?php class PostsController extends AppController { var $name = 'Posts'; var $components = array(‘Account’); function index() { $this->Post->recursive = 0; $this->set('posts', $this->paginate()); } function view($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post.', true)); $this->redirect(array('action'=>'index')); } $this->set(compact('post')); } function add() { if (!empty($this->data)) { $this->Post->create(); if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } } function edit($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid Post', true)); $this->redirect(array('action'=>'index')); } if (!empty($this->data)) { if ($this->Post->save($this->data)) { $this->Session->setFlash(__('The Post has been saved', true)); $this->redirect(array('action'=>'index')); } else { $this->Session->setFlash(__('The Post could not be saved. Please, try again.', true)); } } else { $this->data = $post; } } function delete($id = null) { $conditions = array( 'Post.id'=>$id, ); $post = $this->Post->find('first', compact('conditions')); if (!$post) { $this->Session->setFlash(__('Invalid id for Post', true)); $this->redirect(array('action'=>'index')); } if ($this->Post->del($id)) { $this->Session->setFlash(__('Post deleted', true)); $this->redirect(array('action'=>'index')); } } } ?>
  • 106. これぞ究極!? <?php class PostsController extends AppController { � var $name = 'Posts'; } ?>
  • 108. UploadBehavior class UploadBehavior extends ModelBehavior { function beforeSave(&$model, $options = array()) { if (!$model->data[$model->alias]['image']['error']) { $filename = low($model->alias).DS.$model- >data[$model->alias]['image']['name']; move_uploaded_file( $model->data[$model->alias]['image']['tmp_name'], WWW_ROOT.'img'.DS.$filename); $model->data[$model->alias]['image'] = $filename; } else { unset($model->data[$model->alias]['image']); } return true; } }
  • 109. Post class Post extends AppModel { var $name = 'Post'; var $actsAs = array('Upload');
  • 110. Post class Post extends AppModel { var $name = 'Post'; var $actsAs = array('Upload');
  • 114. 参考になるもの http://thechaw.com/cakebook/source/ app_controller.php AppControllerに 共通処理をまとめてある
  • 120. 参考になるもの 翻訳記事 リファクタリングを考える時期の記事紹介 - cakephper の日記 http://d.hatena.ne.jp/cakephper/ 20090601/1243853035 元記事 5 signals that can indicate its time to re- factor ¦ Mark Story http://mark-story.com/posts/view/5-signals- that-can-indicate-its-time-to-re-factor

Notas do Editor