cakephp2.3.8中何为component

大胆假设,小心求证         记得这句话是以前读高三的时候,一个数学老师(圆头,有点胖胖的老师,不是很记得),经常挂在嘴边的一句话,

对于我们不理解,或者说是无法确定的东西,我们不妨先大胆地去假设,然后再一步一步逼近,去认清那个东西。

让我敬佩的还是高三()时候 的物理老师,正式厉害,我的物理成绩也是妥妥的,做题无比的淡定。以前所有的忧虑情绪皆不见了。做物理题目就是享受。

扯远了。。。

回到正题,caKephp 中所谓的component 是个什么概念呢?不妨大胆假设,小心求证!

其实,在cakephp中,component 这个概念其实就是 controller 中一些想在不同的controller中都能够复用的方法罢了,可以都放到 AppController类中, 

或者,独立出来,放到一个 component 中,执行每一个controller 的时候,会自动加载 comonents  ,只要这个comopnet 有在controller中引用,引用很简单,就是定义 public $components = array('xxxx') ,定义一个这样的属性就可以了。

----------------------------------------------------------------------

 All the business logic should go in my controllers, but what if I want to re-use something elsewhere?

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.

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:

Controller Extensions (“Components”)

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 view
  • beforeFilter(), executed before any controller action logic
  • beforeRender(), executed after controller logic, but before the view is rendered
原文地址:https://www.cnblogs.com/oxspirt/p/6776462.html