`
buliedian
  • 浏览: 1221950 次
  • 性别: Icon_minigender_2
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

CakePHP 21 tips (CakePHP的21条技巧)

阅读更多
  • Easily creating static pages

    I needed to create several pages that didn't use any models and contained static data inside the default layout. My first thought was to create a controller for these pages and define an action for each static page I needed. However, this solution seemed tedious and would make it difficult to quickly add new pages. Enter the pages controller - simply create a view inside the views/pages/ folder and it'll automatically be rendered in /pages. For example, if I created /views/pages/matt.thtml(change to matt.ctp) it would be accessible via http://www.example.com/pages/display/matt

  • Static pages - Adjusting the page title

    If you're using the pages controller and you need to change the page title, add the following to your view:
    <? $this->pageTitle = 'Title of your page.'; ?>

  • Static pages - Adjusting other data sent to the layout

    If you need to send data to the layout (such as a variable indicating what section to highlight on the nav bar), add this to your view:

    <? $this->_viewVars['somedata'] = array('some','data'); ?>

    That array should then be accessible as $somedata inside your layout.

  • Creating a simple admin center

    If you need to create an administrative back-end for your CakePHP site and would like all the actions with administrative capabilities to exist under a specific folder, open up config/core.php and uncomment:
    define('CAKE_ADMIN', 'admin');

    This will then make all actions that are prefixed with "admin_" to be accessible via:
    /admin/yourcontroller/youraction. For instance, if I created an action in my posts controller called "admin_add," I would access this via: www.example.com/admin/posts/add
    From there I could simply password the admin folder to prohibit unwanted users from adding posts.

  • Viewing the SQL queries that are running behind the scenes

    You can easily see the SQL queries that CakePHP is running by adjusting the DEBUG constant in config/core.php. 0 is production, 1 is development, 2 is full debug with SQL, and 3 is full debug with SQL and dump of the current object. I typically have debug set at 2, which renders a table at the bottom of the page that contains SQL debug information.

    If rendering a table at the bottom of your site is constantly breaking your layout during development (especially if you're making AJAX calls and you're getting SQL inside your pages, not just the bottom), you can easily style this table to be hidden by adding this to your CSS:

    #cakeSqlLog { display: none; }

    This will allow you to view debug information in the HTML source code without your layout getting mangled, just don't forget to set debug back to 0 when your site goes live.

  • Multiple sources of documentation

    Don't just rely on the manual . The wiki and the API are invaluable sources of information. The tutorials in the wiki are especially useful, and the API may be daunting at first, but you'll quickly find the information in there is crucial to building a site with CakePHP.

  • Using bake.php

    Bake is a command line PHP script that will automagically generate a model, controller, and views based on the design of your database. I highly recommend using scaffolding to get a prototype going of a table that may change a lot in the beginning. If you're fairly certain the data is not subject to any drastic change, I recommend using bake instead. With bake all the files are generated and written to disk and you can make modifications from there. It saves a lot of time doing the repetitive tasks such as creating associations, views, and the basic CRUD controller operations.

    Using bake is really easy. Once you have a table(s) in your database created, change directories to the /cake/scripts/ folder and run:
    php bake.php

    If you choose to bake interactively it'll walk you through the steps required to create your model, controller, and views. Once everything has been baked I usually go through all the generated code and make custom modifications as needed.

  • Mind permissions when moving cake around

    When I changed from the development server to the live server I tarred up my entire cake directory and scp'd it to the new server. Immediately I started having an issue where any time the debug level was set to 0 (production mode), data would not be returned for certain database calls. This was a bit of a catch 22 since I needed to view debug information to troubleshoot the problem.
    Someone in #cakephp kindly pointed out that permissions on the /app/tmp folder need to be writeable by apache. I changed the permissions to 777 and the issue went away.

  • Complex model validation

    I needed to validate beyond just checking to make sure a field wasn't empty or it matched a regular expression. In particular, I needed a way to verify that the email address users registered with was unique. In the wiki I found this gem: this advanced validation tutorial , which covers some advanced methods of validation that were very useful.

  • Logging errors

    $this->log('Something broke');
    This will log your error to /tmp/logs/ (I initially made the mistake of thinking it would log it to the apache error log)

  • Creating a controller that uses other models

    Suppose you have a controller that needs data from a bunch of different models, simply add this to the top of your controller:

    class yourController extends AppController
    {
    var $uses = array('Post','User');
    }


    This controller would then have access to both the Post and the User model.

  • Creating a model for a table that doesn't actually exist in the database

    I needed a way to create a model and controller without actually having an associated table in the database. I particularly wanted to make use of the $validate array so I could easily validate my fields and keep the validation logic in the model. CakePHP will throw an error if you create a model for a table that doesn't exist. Adding this to the model fixed the problem:
    var $useTable = false;

    You can use this to change tables names as well.
    var $useTable = 'some_table';

  • Call exit() after redirecting

    This should be no surprise to anyone who has done any serious web development in the past, but make sure you call exit() after running $this->redirect() if there's code afterward that you don't want to run. I've always done this in the past, but I made the assumption that $this->redirect() would make an exit call for me (which it didn't).

  • Advanced model functions

    Unless you delve in to the API, there are some very useful model functions at your disposal you might not know exist. I highly recommend reading over the Model Class Reference at least once. Here's a few key functions I wasn't aware of that I found to be very useful:
    • generateList() - I use this function primarily to populate select boxes with data from associated tables
    • query() - Sometimes you just need to write your own SQL
    • findCount() - Returns number of rows matching given SQL condition
    • hasAny() - Returns true if a record that meets the given conditions exists.
    Again, I highly recommend reading over the entire model class reference , you'll be surprised at what you learn.
  • Inserting multiple rows in succession

    I had a situation where I needed to iterate through a list of items and insert new rows for each. I quickly discovered that if you insert an item and then immediately insert another, the item that is inserted next doesn't insert at all. Instead the previously inserted row was being updated. For example:

    $items = array('Item 1','Item 2','Item 3');
    foreach ($items as $item) {
    $this->Post->save(array('Post' => array('title' => $item)));
    }


    This code will result in a single entry in the posts table: "item 3." CakePHP inserted "item 1", but then updates it to become "item 2," then "item 3" because $this->Post->id gets the value of the last inserted ID. Normally this functionality is very useful, but in this particular instance it was not. I found was to setting $this->Post->id = false after each insert solved the problem.

    Update: Someone emailed me and apparently the proper way of doing this is to call create() to initialize the model and then set/save your new data.

  • Inserting logic before or after controller functions

    Suppose you needed an array of colors to be available to every view rendered by your controller but you don't want to have to define this data in every action. Using the beforeRender() callback will allow you to do this:

    function beforeRender() {
    $this->set('colors',array('red','blue','green');
    }


    This would make $colors accessible in every view rendered by that controller. beforeRender() is called after the controller logic and just before a view is rendered.
    There's also beforeFilter() and afterFilter() , which are called before and after every controller action. For more information, read up on callbacks in the models section of the manual.

  • Adding a WYSIWYG editor to CakePHP

    I found this great tutorial on getting TinyMCE set up with CakePHP. Basically you just link the tiny_mce .js file to your page and then add a small bit of init code to every page that you want textareas to be converted into TinyMCE editors.

  • Writing your own SQL for HABTM relationships

    I had an issue with trying to create a HABTM (has-and-belongs-to-many) relationship where I needed to specify my own SQL statement. According to the docs (at the time of this writing) you should set finderSql in your model, but according to the cakePHP source you should set finderQuery instead. It's just a foul-up in the docs, but I figured it'd be worth noting to save others from having to figure it out for themselves. Trac ticket here: https://trac.cakephp.org/ticket/1217

  • Sending email

    I found two tutorials in the wiki: Sending email and Sending email with PHPMailer
    I highly recommend the latter of the two, sending emails with PHPMailer is more secure and there's less of a headache because you don't have to deal with constructing the mail headers yourself.

  • Customizing HTML generated by the Helper

    I needed to change the default <option> generated when I called $html->selectTag() to say something like "Please Select" rather than an empty space (default). I also wanted radio buttons to have labels so the user doesn't have to click exactly on the radio button itself but can instead click anywhere on the text associated with it.

    Create the file /app/config/tags.ini.php and add the following:
    ; Tag template for a input type='radio' tag.
    radio = "<input type="radio" name="data[%s][%s]" id="%s" %s /><label for="%3$s">%s</label>"

    ; Tag template for an empty select option tag.
    selectempty = "<option value="" %s>-- Please Select --</option>"


    You can get a full list of available tags in /cake/config/tags.ini.php. I wouldn't recommend modifying that file, however, because you could lose your changes when you upgrade CakePHP.

  • Creating a custom 404 error page

    If you need to change the page that users see when a document is not found, create:
    /app/views/errors/error404.thtml

分享到:
评论

相关推荐

    PHP的框架之CakePHP-CakePHP教程

    打包下载,里面有CakePHP的框架源码,下载后可直接使用,版本是1.1的,稳定版;...CakePHP的使用技巧介绍;CakePHP开发的网站源码参考;CakePHP的中文资料很少,大部分是英文的,希望对大家有用,谢谢!

    PHP的框架之CakePHP-CakePHP教程终极教程

    打包下载,里面有CakePHP的框架源码,下载后可直接使用,版本是1.1的,稳定版;...CakePHP的使用技巧介绍;CakePHP开发的网站源码参考;CakePHP的中文资料很少,大部分是英文的,希望对大家有用,谢谢!

    cakephp php-framework

    There are two main ways to get a fresh copy of CakePHP. You can either download an archive copy (zip/tar.gz/tar.bz2) from the main website, or check out the code from the git repository. To download ...

    cakephp-1.2 manual

    通过阅读《CakePHP 1.2 手册》,开发者不仅能掌握该框架的基本用法,还能了解到最佳实践和高级技巧,从而提高开发效率和项目质量。虽然手册是英文版,但详细的解释和示例代码将有助于你无障碍地学习。在实际开发过程...

    CakePHP 3.4 开发手册文档 CakePHP Cookbook Documentation Release 3.4

    ### CakePHP 3.4 开发手册文档概览 #### CakePHP 一瞥 CakePHP 是一款基于 PHP 的快速开发框架,它强调采用约定优于配置(Convention Over Configuration, CoC)的原则来简化开发过程,使得开发者能够快速构建稳定...

    cakephp 框架1.3.11版本

    - **chinaz.com.txt**:这个文件名暗示可能是一份从chinaz.com(站长之家)网站上获取的资料或者相关教程,可能包含了与 CakePHP 开发相关的技巧、最佳实践或者社区资源。 - **cakephp-cakephp-3b830a4**:看起来像...

    CakePHP 1.2 API 中文文档

    **CakePHP 1.2 API 中文文档** CakePHP 是一个基于MVC(Model-View-Controller)架构的开源PHP框架,它旨在简化Web应用程序的开发,并提高开发效率。 CakePHP 1.2 API 中文文档是针对这个版本的详细技术参考,为...

    cakephp手册完整打印版

    通过这份详尽的手册,无论是初学者还是有经验的开发者,都能深入理解并掌握CakePHP框架的核心概念和实际应用技巧。无论是在项目开发初期的规划阶段,还是在后期的维护和优化中,它都将是一份宝贵的参考资料。

    cakephp-1.3.21.zip

    《CakePHP 1.3.21:框架详解与应用实践》 CakePHP是一个基于Model-View-Controller(MVC)架构模式的开源PHP框架,它致力于简化Web应用程序的开发,提供了一套强大的工具和约定,使开发者能够快速构建高质量的网站...

    CakePHP PHP MVC框架

    1. **路由配置**:CakePHP的路由系统允许开发者自定义URL模式,使URL更友好,易于理解。 2. **自动验证**:对表单数据进行验证,确保输入符合预设规则。 3. **ORM(对象关系映射)**:通过ActiveRecord模式,提供了...

    CakePHP使用ajax传值

    CakePHP框架中实现Ajax传值是通过AJAX (Asynchronous JavaScript and XML) 技术与后端的CakePHP控制器进行数据交换的一种方式。通常在Web开发中,Ajax用于创建更为动态和响应快速的用户界面。当用户与页面上的元素...

    CakePHP v2.3.0.zip

    CakePHP v2.3.0是该框架的一个特定版本,发布于2012年,提供了许多改进和新特性,使得开发者可以更轻松地构建安全、高效且可维护的Web应用。 **1. MVC架构**:MVC模式是软件设计中的经典模式,将应用程序分为三个...

    CakePHP 3.5 开发手册文档 CakePHP Cookbook Documentation Release 3.5/共900页 PDF

    - **Debugging**: 调试工具和技巧。 - **Object settings/configuration**: 对象配置设置。 - **Cache**: 缓存机制及其配置。 - **Core**: 核心类和组件的介绍。 - **Console**: 命令行界面的使用方法。 - **...

    phpmvc框架cakephp

    2. **目录结构**:CakePHP有清晰的目录结构,如APP(应用程序)、VENDOR(第三方库)、WEBROOT(网页资源)等,这有助于保持代码组织有序。 3. **路由系统**: CakePHP的路由机制允许开发者灵活地定义URL模式与控制...

    cakephp 框架

    以下是对 CakePHP 框架的详细阐述: 一、简介 CakePHP 是一个遵循 Model-View-Controller 架构模式的 PHP 框架,它使用了类似于 Ruby on Rails 的约定优于配置(Conventions over Configuration)原则,减少了...

    cakephp-cakephp-2.0.0-beta-0-g402934f.zip

    标题中的"cakephp-cakephp-2.0.0-beta-0-g402934f.zip"表明这是一个针对CakePHP 2.0.0 beta版本的压缩包,其中可能包含了框架的核心组件、示例代码以及相关的文档资料。 在描述中提到,CakePHP是“借鉴Raid on ...

Global site tag (gtag.js) - Google Analytics