`

CakePHP: 一些资料和记录

    博客分类:
  • PHP
 
阅读更多
CakePHP配置: http://panyongzheng.iteye.com/blog/1961699

Cake的全局常量及方法 http://docs.30c.org/cakephp/globalconstants.html
CakePHP2命名规范 http://www.ruiwant.com/cakephp-conventions.html
常用的8个.htaccess代码 http://help.vit.cn/item/78.html
CakePHP应用开发 第七章 视图:创建用户界面(2)  http://www.21haolou.com/articles/show/19
CakePHP2 Request请求对象 http://www.ruiwant.com/cakephp-request-object-tutorial-basic.html
cakephp 中的controller 变量 http://www.phpgz.com/html/framework/kcakephp/20090724/758.html
CakePHP 2.x CookBook 中文版 第七章 模型 之 保存数据 http://www.cnblogs.com/matchless/archive/2013/02/04/2891845.html
Model定义& 关联关系定义 http://www.1x3x.net/cakephp/model.html
CakePHP控制器向视图传值总结 http://blog.csdn.net/simengsiyu/article/details/12713671
CakePHP自动填充表单域模型 http://www.91r.net/ask/6848429.html
CakePHP中Router的机制和使用方法 http://flyer0126.iteye.com/blog/1013255
cakephp路由配置 http://www.jiangkunlun.com/2010/12/cakephp%E8%B7%AF%E7%94%B1/
CakePHP你必须知道的21条技巧 http://tech.idv2.com/2007/10/19/21-tips-you-must-know-about-cakephp/




检索数据
如前所述,模型层的角色之一是从多种类型的存储中获取数据。CakePHP 的模型类拥有一些 功能,能够帮助你搜索数据、把数据排序、分页以及过滤。模型中最常用的功能是 Model::find() 方法。
find
find(string $type = 'first', array $params = array())

find 方法是所有检索数据方法中的多功能机器。$type 参数值可以是 'all' 、 'first' 、 'count' 、 'list' 、'neighbors' 或 'threaded',或 者任何自定义查询类型。切记 $type 是大小写敏感的。使用大写字母(如 All )将 无法得到期望的结果。
$params 用于向各种类型的 find() 方法传递所有参数,默认有如下的键,都是可选的:
array(
    'conditions' => array('Model.field' => $thisValue), //查询条件数组
    'recursive' => 1, //整型
    //字段名数组
    'fields' => array('Model.field1', 'DISTINCT Model.field2'),
    //定义排序的字符串或者数组
    'order' => array('Model.created', 'Model.field3 DESC'),
    'group' => array('Model.field'), //用来分组(*GROUP BY*)的字段
    'limit' => n, //整型, 页长度
    'page' => n, //整型,页下标,1开始
    'offset' => n, //整型,起点位置,0开始
    'callbacks' => true //其他值可以是 false, 'before', 'after'
)







Controller : http://book.cakephp.org/2.0/en/controllers.html
View : http://book.cakephp.org/2.0/en/views.html
Model : http://book.cakephp.org/2.0/en/models.html

修改模板后缀:
CakePHP默认模板文件的后缀为ctp,
如果想修改此后缀,可以在/app/Controller/AppController.php文件中添加以下代码:
public $ext = '.html';


1. 定义全局变量:可以在app\webroot\index.php,使用define('CONTEXT_PATH', "/");方法来定义;

2. 主键:$primaryKey,如果主键字段不为'id',COC无法发挥的时候,你可以通过该变量来指定主键字段名字。

3. 创建新的布局:创建任意数量的layout,只要把他们放在app/views/layouts目录,并且在你的controller action里边使用controller的$layout变量或者setLayout()方法来切换layout。
在方法里面使用:$this->layout = 'administrator';

4. 模型的对象关联:hasOne,hasMany,belongsTo,hasAndBelongsToMany。http://lesorb.iteye.com/blog/736694, Cakephp查询关联表的方法总结 http://www.php1.cn/article/6759.html

5. CakePHP中回调函数的使用 http://www.cnblogs.com/mafeifan/archive/2013/08/21/3273097.html

6. 帮助类:HTML Helper,Ajax helper,Javascript helper,Number helper,Text helper,Time helper
echo $this->Html->image($coll["web_path"], array('alt' => 'CakePHP','width'=>'56','height'=>'56'));
echo $this->Html->link(
    'Enter',
    '/pages/home',
    array('class' => 'button', 'target' => '_blank')
);
echo $this->Html->link(
    $this->Html->image("recipes/6.jpg", array("alt" => "Brownies")),
    array(
        'controller' => 'recipes',
        'action' => 'view',
        'id' => 6,
        'comments' => false
    )
);//好像无效
echo $this->Html->link(
    $this->Html->image("recipes/6.jpg", array("alt" => "Brownies")),
    "recipes/view/6",
    array('escape' => false)
);
echo $this->Html->link(
                        $this->Html->image($coll["web_path"], array('alt' => 'CakePHP','width'=>'56','height'=>'56')),
                        array(
                            'controller' => 'recipes',
                            'action' => 'view',
                            'id' => 6,
                            'comments' => false
                        ),
                        array('escape' => false)
                    );

http://book.cakephp.org/2.0/en/core-libraries/helpers/html.html


7.Ajax方式接受传进Controller的参数
get :
$this->request->query['page']
post:
[color=darkblue]$this-request->data['Post']['title'];
,没测试成功。
$this->request->data["password"],测试成功。
否则直接使用PHP自己的:$_GET,$_POST对象获取数据
其他:
A: $this->redirect(array('controller' => 'login', 'action' => 'index',"message"=>"错误信息.")); 传信息进来,使用$this->request->params["named"]["message"]读取
Ajax返回:
$php_json = json_encode($list);
        $result = array(
            'rows' => $list,
            'page' => 1,
            'total' => 2,
            'records' => 1
        );
        return new CakeResponse(array('body' => json_encode($result), 'status' => 200));


8. 保存数据:
// 创建新记录: id 没有设置或设置为 null
$this->Recipe->create();
$this->Recipe->save($this->request->data);

// 更新记录: id 被设置为一个数字值
$this->Recipe->id = 2;
$this->Recipe->save($this->request->data);


//只更新某个字段
$this->User->id=$users["User"]["user_id"];
$this->User->saveField('login_error_num', 10);


9.Controller使用其他Model
var $uses = array("Accesse", "Site");

这样就可以直接在这个Controller使用$this->Site->?????了。

10.Controller使用其他组件
var $components = array('Session', 'Email');


11按钮的样式:由于From助手只提供submit的input类型,button类型的样式有点问题,所以换一种方式生成按钮:
echo $this->Form->submit('按钮',array("type"=>"button"));
,
这样虽然改变了按钮的类型是button,而不是submit,但因为按钮的外面被div包含,所以几个按钮在一起的时候,总是要换行,现在改变外面使用span来包含,就解决问题:
echo $this->Form->submit('保存',array("type"=>"button","name"=>"save","div"=>false,"before"=>"<span class='submit'>","after"=>"</span>"));

增加样式:
input[type=button] {
    display: inline;
    font-size: 110%;
    width: auto;
}
form .submit input[type=button] {
    background:#62af56;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#76BF6B), to(#3B8230));
    background-image: -webkit-linear-gradient(top, #76BF6B, #3B8230);
    background-image: -moz-linear-gradient(top, #76BF6B, #3B8230);
    border-color: #2d6324;
    color: #fff;
    text-shadow: rgba(0, 0, 0, 0.5) 0px -1px 0px;
    padding: 8px 10px;
}
form .submit input[type=button]:hover {
    background: #5BA150;
}
input[type=button] {
    font-weight:normal;
    padding: 4px 8px;
    background: #dcdcdc;
    background-image: -webkit-gradient(linear, left top, left bottom, from(#fefefe), to(#dcdcdc));
    background-image: -webkit-linear-gradient(top, #fefefe, #dcdcdc);
    background-image: -moz-linear-gradient(top, #fefefe, #dcdcdc);
    background-image: -ms-linear-gradient(top, #fefefe, #dcdcdc);
    background-image: -o-linear-gradient(top, #fefefe, #dcdcdc);
    background-image: linear-gradient(top, #fefefe, #dcdcdc);
    color:#333;
    border:1px solid #bbb;
    -webkit-border-radius: 4px;
    -moz-border-radius: 4px;
    border-radius: 4px;
    text-decoration: none;
    text-shadow: #fff 0px 1px 0px;
    min-width: 0;
    -moz-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.2);
    -webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.2);
    box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.3), 0px 1px 1px rgba(0, 0, 0, 0.2);
    -webkit-user-select: none;
    user-select: none;
}


11.引入js和css文件:
echo $this->Html->css('cake.generic');
echo $this->Html->script("site/Admins/admin_site");


12.输出图片,一些图片直接使用url,但是有不是存放在img路径下,那么会被要求经过controller,比如图片位置:
http://localhost/apps/EnterpriseSite/storage_file/storage_file_tmp/p189gt0ekfm3f17
t01bvsolgjsu4.png,其中EnterpriseSite是app的根目录,那
App::import("Vendor", "EnterpriseSiteUtils");
class StorageFileController extends AppController{
    var $helpers = array('Helper');

    public function storage_file_tmp() {
        //$this->Html->image(EnterpriseSiteUtils::getContextPath()."/storage_file/storage_file_tmp/p189gt0ekfm3f17t01bvsolgjsu4.png");
        //$filename=   EnterpriseSiteUtils::getContextPath()."/storage_file/storage_file_tmp/p189gt0ekfm3f17t01bvsolgjsu4.png";
        $filename=   WWW_ROOT."../../storage_file/storage_file_tmp/p189gt0ekfm3f17t01bvsolgjsu4.png";
        if (!file_exists($filename)) {
            throw RuntimeException("File $filename not found");
        }
        header("Content-Type: png");
        header("Content-Length: ".filesize($filename));
        readfile($filename);
    }
}
,就可以直接使用url访问存放在非Img目录下面的图片来显示了。
当然,也可以配置.htaccess文件(见配置的文章)

[color=darkblue]13 自定义主题 [/color]http://www.cnblogs.com/matchless/archive/2013/01/31/2886519.html
详细参考链接,经过实践,得到几个注意的地方
1.最好使用助手,否则问题会碰到一大堆,因为助手支持了主题。
2.主题的名称第一个字母最好大写,否则到网上的服务器可能出问题。

13. 改变controller默认视图
在controller里面定义一个变量:
public $name = 'User'; //指定这个controller使用的是User视图


14. URL
A:
$link = $this->Html->link($title, $url, array('class' => 'edit'));
,创建一个以a为标签的连接.
B:
echo $this->Html->url(array(
    "controller" => "posts",
    "action" => "view",
    "bar"
));


15. 引入第三方库
App::import("Vendor", "EnterpriseSiteUtils");  


16. 重定向和跳转
A: 重定向:
$this->redirect(array('controller' => 'login', 'action' => 'index'));


17. SESSION
$this->Session->write('Person.eyeColor', 'Green');//设定session, 注意:这里的key有点,那么保存到session的时候是以对象的方式保存
$green = $this->Session->read('Person.eyeColor');

检查是否被设定: SessionComponent::check($name)
删除session数据: SessionComponent::delete($name)
销毁session: SessionComponent::destroy()

18. 手动创建Model和执行自定义sql
$Menu = new Model("menu_id","menus");
$list = $Menu->query("select * FROM wfms_menus where company_id=1");


19. 事务处理 http://www.cakephp.cn/forum.php?mod=viewthread&tid=620
http://www.cnblogs.com/anhelida/p/3987339.html
在ocntroller使用事务例子:
http://stackoverflow.com/questions/18032532/cake-php-2-3-x-transaction
Model:Product,Price,Property增加下面三个方法
function begin() {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $db->begin($this);
    }

    function commit() {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $db->commit($this);
    }
    function rollback()
    {
        $db =& ConnectionManager::getDataSource($this->useDbConfig);
        $db->rollback($this);
    }

Controller:
$datasource = $this->Product->getDataSource();
try{
    $datasource->begin();
    if(!$this->Product->save($data)
        throw new Exception();

    if(!$this->Price->save($data_one)
        throw new Exception();

    if(!$this->Property->save($my_data)
        throw new Exception();

    $datasource->commit();
} catch(Exception $e) {
    $datasource->rollback();
}


20. 临时文件夹权限: Could not apply permission mask
http://stackoverflow.com/questions/20189251/after-setting-cache-mask-at-777-the-permissions-generated-on-the-cache-file-is
这里可能是解决方式:http://stackoverflow.com/questions/12718331/ocasional-error-warning-when-cakephp-is-writing-to-the-cache同时给app/tmp路径777权限。


cakephp修改时区 http://blog.csdn.net/php_byrnes/article/details/37507149
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics