大膽假設,當心求證 記得這句話是之前讀高三的時候,一個數學老師(圓頭,有點胖胖的老師,不是很記得),常常掛在嘴邊的一句話,
php
對於咱們不理解,或者說是沒法肯定的東西,咱們不妨先大膽地去假設,而後再一步一步逼近,去認清那個東西。html
讓我敬佩的仍是高三()時候 的物理老師,正式厲害,個人物理成績也是妥妥的,作題無比的淡定。之前全部的憂慮情緒皆不見了。作物理題目就是享受。session
扯遠了。。。app
回到正題,caKephp 中所謂的component 是個什麼概念呢?不妨大膽假設,當心求證!ide
其實,在cakephp中,component 這個概念其實就是 controller 中一些想在不一樣的controller中都可以複用的方法罷了,能夠都放到 AppController類中, this
或者,獨立出來,放到一個 component 中,執行每個controller 的時候,會自動加載 comonents ,只要這個comopnet 有在controller中引用,引用很簡單,就是定義 public $components = array('xxxx') ,定義一個這樣的屬性就能夠了。
spa
----------------------------------------------------------------------code
All the business logic should go in my controllers, but what if I want to re-use something elsewhere?component
Good question. You will almost always have to create some complex logic for an application, and you usually want to re-use part of that logic. The most common way to include an application-wide function or variable so that it's available in every controller is to define it in your AppController file. This file basically consists of an empty class that extends Cake's internal Controller class, and is located in the /cake/ directory. You can move it to your /app/
directory and create methods that will be available in all of your custom controllers that extend AppController. Even if you're not planning to use an AppController at first, it's often wise to create custom controllers which extend AppController rather than the Controller
class.orm
An easy way to create custom classes handling a specific task is to create a component. Components can be loaded automatically in controllers (and only inside controllers) by adding a variable named $components
:
var $components = array('Session', 'MyCustomComponent');
CakePHP comes with some default components such as Session, which offers convenient ways to organize session data, or RequestHandler, which can be used to determine more information about HTTP requests. These are documented in the CakePHP manual:
A Component is a class that aids in controller logic. If you have some logic you want to share between controllers (or applications), a component is usually a good fit. As an example, the core EmailComponent class makes creating and sending emails a snap. Rather than writing a controller method in a single controller that performs this logic, you can package the logic so it can be shared.
Controllers are also fitted with callbacks. These callbacks are available for your use, just in case you need to insert some logic between CakePHP’s core operations. Callbacks available include:
afterFilter()
, executed after all controller logic, including the rendering of the viewbeforeFilter()
, executed before any controller action logicbeforeRender()
, executed after controller logic, but before the view is rendered