1 cakephp中,control层自动按其命名去寻找model层,比如按TaskController,则关联Task的这个model
如果不关联,可以这样
<?php
class BooksController extends AppController {
var $name = 'Books';
var $uses = array();
function index() {
$this->set('page_heading', 'Packt Book Store');
$book = array (
'book_title' => 'Object Oriented Programming
with PHP5',
'author' => 'Hasin Hayder',
'isbn' => '1847192564',
'release_date' => 'December 2007'
);
$this->set($book);
$this->pageTitle = 'Welcome to the Packt Book Store!';
}
}
?>
其中var $uses = array();则表明不关联任何model,当然如果要关联的话,则可以
$uses = array ( 'ModelName1', 'ModelName2' ) ;
上面的程序中,配合的模版index.thtml为
<h2><?php echo $page_heading; ?></h2>
<dl>
<lh><?php echo $bookTitle; ?></lh>
<dt>Author:</dt><dd><?php echo $author; ?></dd>
<dt>ISBN:</dt><dd><?php echo $isbn; ?></dd>
<dt>Release Date:</dt><dd><?php echo $releaseDate; ?></dd>
</dl>
则可以把$this->set($book);中的book数组的内容,自动输出到页面中去了.注意用这种方法的话,象
'book_title' => 'Object Oriented Programming
中的book_title,在页面中的输出模版是变为<?php echo $bookTitle; ?>,就是没了中间的下划线了
2 再来看个例子
<?php
class UsersController extends AppController {
var $name = 'Users';
var $uses = array();
function index() {
if (!empty($this->data)) {
//data posted
echo $this->data['name'];
$this->autoRender = false;
}
}
}
?>
模版:
<?php echo $form->create(null, array('action' => 'index'));?>
<fieldset>
<legend>Enter Your Name</legend>
<?php echo $form->input('name'); ?>
</fieldset>
<?php echo $form->end('Go');?> .
$this->data,用来保存post过来的数据, <?php echo $form->create(null, array('action' => 'index'));?>中,
调用cakephp的formhelper工具方法,第一个参数null表明不和任何model绑定,之后的array('action' => 'index'));?>
表明是要使用controll层中的index().
echo $this->data['name'];
$this->autoRender = false;
中,$this->data['name'];输出结果,$this->autoRender = false;在controll层中设置输出结果,不跟view绑定输出.
3 redirect跳转
class UsersController extends AppController {
var $name = 'Users';
var $uses = array();
function index() {
if (!empty($this->data)) {
$this->redirect(array('controller'=>'users',
'action'=>'welcome', urlencode($this->data['name'])));
}
}
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));
}
}
这里的意思是,如果有页面提交的参数,则用redirect跳转到userscontroller中的welcome这个action中,同时传递参数name.
4 可以在app里写个基类,比如
class AppController extends Controller {
....
}
放在app目录下
然后其他的继承之
class BooksController extends AppController {
...
}
5 cakephp的组件
在controll中的component目录中,写组件 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;
}
}
?>
要使用时
class BooksController extends AppController {
var $name = 'Books';
var $uses = array();
var $components = array('Util');
$id = $this->Util->strip_and_clean($id,$books);
......