一步一步学习CakePHP(二)controllers

我们已经知道,controllers就是负责处理客户端的请求,实现models和views的交互。在CakePHP中,在controller中的每一个公共的方法都被叫做“action”,每一个action就会代表一个url,在浏览器请求此url时,控制器将会使用model来操作和处理数据,当数据被处理后,那么控制器把结果从model被传送到view。

我们接下来会学习控制器的具体细节。

一:与model的交互

一般说来,一个控制器会处理一个对于model的业务逻辑,控制器就会自动地找到对应的model。但是这也不是绝对的,有时,我们也需要某控制器不依赖于任何model,这时候,需要配置控制器。举例说明,

控制器:books_controller.php

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class BooksController extends AppController{
    var $name = 'Books';
    var $uses = array();
    function index(){
    }
}

?>

view:index.ctp

<h2>the China-pub website</h2>
<p>New Books Comming Soon!</p>

在这个控制器中,定义了一个属性$uses,它明确定义了控制器相关的model,如果不定义,控制器将会根据名称来找到对应的model,如果赋予一个空的数组,也就是说,没有用的任何的model。

clip_image002

综上:控制器和model的关联有两种方式,一是自动绑定,而是人为手工绑定。如:$uses = array ( 'ModelName1', 'ModelName2' ) 。

二:传送数据到view

CakePHP为控制器的action定义恰当的view文件,控制器也提供给view处理完成后的数据。如:$this->set($book);可以用set自动把数据传送到view。

控制器:books_controller.php

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class BooksController extends AppController{
    var $name = 'Books';
    var $uses = array();
    function index(){
        $this->set('page_heading','china-pub book store');
        $book = array(
            'book_title' => 'asp.net 3.5服务器控件开发',
            'author' => '郑健',
            'release_date' => '2009.2'
        );
        $this->set($book);
        $this->pageTitle = '欢迎来到china-pub';
    }
}
?>

view:index.ctp

<h2><?php echo $page_heading; ?></h2>
<dl>
<lh><?php echo $bookTitle; ?></lh>
<dt>author:</dt><dd><?php echo $author; ?></dd>
<dt>Release Date:</dt><dd><?php echo $releaseDate; ?></dd>
</dl>

clip_image004
三:带有参数的控制器action

控制器:books_controller.php

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class BooksController extends AppController{
    var $name = 'Books';
    var $uses = array();
    function index( $id = 0 ){
        $this->set('page_heading','china-pub book store');
        $book = array(
            '0' => array(
                'book_title' => 'asp.net 3.5服务器控件开发',
                'author' => '郑健',
                'release_date' => '2009.2'
            ),
            '1' => array(
                'book_title' => '银光志',
                'author' => '魏永超',
                'release_date' => '2009.12'
            )
        );
        $id = intval($id);
        if( $id <0 || $id >= count($book)){
            $id = 0;
        }
        $this->set($book[$id]);
        $this->pageTitle = '欢迎来到china-pub';
    }
}
?>

接下来我们看下列链接

http://localhost:8080/applogic/Books/index/0

clip_image006

http://localhost:8080/applogic/Books/index/1

clip_image008

http://localhost:8080/applogic/Books/index/aaa

clip_image010

如果存在多个参数的话,举例说明:

控制器,maths_controller.php

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class MathsController extends AppController{
    var $name = 'Maths';
    var $uses = array();

    function add_digits($digit1 = 0, $digit2 = 0, $digit3 = 0 ){
        $sum = intval($digit1) + intval($digit2) + intval($digit3);
        $this->set('sum',$sum);
    }
}
?>

view:

<h2>The sum is equal to <?php echo $sum; ?></h2>

clip_image012

四:从view中获取数据

users_controller.php

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class UsersController extends AppController{
    var $name = 'Users';
    var $uses = array();
/*
* 控制器中的$data,它用来存放从HTML表单传过来的POST数据。
*/
    function index(){
        if(!empty ($this->data)){
            echo $this->data['姓名'];
            //不用渲染任何view
            $this->autoRender = false;
        }
    }
}
?>

view:index.ctp

<?php echo $form->create(null, array('action' => 'index')); ?>
<fieldset>
<legend>请输入您的姓名:</legend>
<?php echo $form->input('姓名') ?>
</fieldset>
<?php echo $form->end('go'); ?>

clip_image014

clip_image016

如果输入一个姓名,并且提交,$data会被POST数据填充,$this->data将不为空,那么在浏览器上就会打印出名字来。

五:重定向
在PHP程序中,我们使用header(),CakePHP中,使用redirect()作用于action。

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class UsersController extends AppController{
    var $name = 'Users';
    var $uses = array();
/*
* 控制器中的$data,它用来存放从HTML表单传过来的POST数据。
*/
    function index(){
        if(!empty ($this->data)){
            $this->redirect(array('controller'=>'users',
                    'action'=>'welcome',urlencode($this->data['姓名'])));
        }
    }
    a
    function welcome($name=null){
        if(empty ($name)){
            $this->Session->setFlash('Please provide your name!',true);
            $this->redirect(array('controller'=>'users','action'=>'index'));
        }
        $this->set('name', urldecode($name));
    }
}
?>

clip_image018

clip_image020
六:AppController

我们知道,CakePHP中,所定义的控制器都是从AppController继承而来,也就是说,它是所有控制器的父类,那么我们就可以在AppController中定义公共的方法,在所有的控制器中都可以使用。

如:我们修改前面的代码:

在app文件夹中增加:app_controller.php

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class AppController extends Controller{
    function strip_and_clean($id,$array){
        $id = intval($id);
        if($id < 0 || $id >= count($array)){
            $id = 0;
        }
        return $id;
    }
}
?>

修改books_controller.php

<?php
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
class BooksController extends AppController{
    var $name = 'Books';
    var $uses = array();
    function index( $id = 0 ){
        $this->set('page_heading','china-pub book store');
        $book = array(
            '0' => array(
                'book_title' => 'asp.net 3.5服务器控件开发',
                'author' => '郑健',
                'release_date' => '2009.2'
            ),
            '1' => array(
                'book_title' => '银光志',
                'author' => '魏永超',
                'release_date' => '2009.12'
            )
        );
        $id = $this->strip_and_clean($id, $book);
        $this->set($book[$id]);
        $this->pageTitle = '欢迎来到china-pub';
    }
}
?>

我们可以得到相同的效果

七:在控制器中使用components

在/app/controllers/components中创建util.php

<?php
   class UtilComponent extends Object
   {
      function strip_and_clean ( $id, $array) {
         $id = intval($id);
         if( $id < 0 || $id >= count($array) ) {
               $id = 0;
         }
         return $id;
      }
   }
   ?>

删除在AppController中定义的strip_and_clean方法

调用:

var $components = array('Util');

$id = $this->Util->strip_and_clean($id);

这样我们也可以得到相同的效果。

posted @ 2010-05-23 03:45  sunfishlu  阅读(5371)  评论(0编辑  收藏  举报