惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - sunfishlu

一步一步学习Windows Azure(二)Azure之Hello World 一步一步学习Windows Azure(一)概述 一步一步学习CakePHP(三)model - sunfishlu 一步一步学习CakePHP(一)基本概念 JQuery写的个性导航菜单 - sunfishlu JQueryUI(五):Dialog(第二部分) JQueryUI(四):Dialog(第一部分) - sunfishlu JQueryUI(三):Accordion JQueryUI(二):Tabs(第二部分) JQueryUI(一):Tabs(第一部分) - sunfishlu - 博客园 封装的Ext Grid javascript与dom编程(五)ajax 无法在Web服务器上启动调试。您不具备调试此应用程序的权限,此项目的URL位于Internet区域。 - sunfishlu - 博客园 ToolTip(图片文字) with Jquery - sunfishlu Ext中combobox在Grid里显示问题 javascript与dom编程(四)animation(例)Tooltips javascript与dom编程(三)animation - sunfishlu extjs grid设置某列背景颜色 javascript与dom编程(二)Event
一步一步学习CakePHP(二)controllers
sunfishlu · 2010-05-23 · via 博客园 - sunfishlu

我们已经知道,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);

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