CakePHP 2.x CookBook Chapter 5 controller Components

Source: Internet
Author: User

A component is a logical package shared among multiple controllers. If you find that you want to copy and paste something between controllers, you should consider encapsulating some functions in a component. CakePHP also comes with a set of beautiful and useful core components: Security (Security) Sessions (Session) Access control lists (Access control List) Emails (email) cookiesAuthentication (permission verification) Request handling (Request processing) Pagination (paging) detailed information of these components are in their respective chapters. Now we will show you how to build your own components. Creating components keeps the Controller code clean and tidy, and allows you to reuse code in multiple projects. Some core components of the Configuration component need to be configured. The required components include authorization, Cookie, and email. For general components, it is usually configured in the $ components array or the beforeFilter method of the controller: 1 class PostsController extends AppController {2 public $ components = array (3 'auth' => array (4 'authorization' => array ('controller '), 5 'loginaction' => array ('controller' => 'users', 'Action' => 'login') 6 ), 7 'cookiemonster' => array ('name' => 'cookiemonster') 8). This is an example of using the $ components array to configure components. All core components can be configured in this way. You can also configure components in the beforeFilter () method of the controller. This method is usually used when you need to associate the result of a function with a component attribute. The above example can also be expressed as: 1 public function beforeFilter () {2 $ this-> Auth-> authorize = array ('controller '); 3 $ this-> Auth-> loginAction = array ('controller' => 'users', 'Action' => 'login '); 4 5 $ this-> Cookie-> name = 'cookiemonster'; 6} however, it is also possible that the specific configuration options of a component must be in the beforeFilter () of the controller () set before running. Finally, some components allow you to set configuration options in the $ components array: 1 public $ components = array (2' DebugKit. toolbar '=> array ('panels' => array ('History', 'session') 3). You can check the relevant documentation to determine which configuration options are provided for each component. ClassName is a public setting option. You can use this to create an alias for the component. This option is useful when you want to replace $ this-> Auth or other public components with a custom implementation. 1 // app/Controller/PostsController. php 2 class PostsController extends AppController {3 public $ components = array (4 'auth' => array (5 'classname' => 'myauth' 6) 7 ); 8} 9 10 // app/Controller/Component/MyAuthComponent. php11 App: uses ('authcomponent', 'controller/component '); 12 class MyAuthComponent extends AuthComponent {13 // Add your code to override the core AuthComponent14} in the controller of the previous example $ thi The alias s-> Auth is MyAuthComponent. Annotations use aliases for any component with aliases, including references in other components. Using components once you have included some components in the controller, it is very easy to use. Each component in the controller is used as an attribute. If you have added SessionComponent AND the CookieComponent to the Controller, you can access them as follows: 1 class PostsController extends AppController {2 public $ components = array ('session ', 'cookies'); 3 4 public function delete () {5 if ($ this-> Post-> delete ($ this-> request-> data ('Post. id ') {6 $ this-> Session-> setFlash ('Post deleted. '); 7 $ this-> redirect (array ('action' => 'index ')); 8} 9} annotation because the model added to the Controller as an attribute shares the same 'namespace 'with the component, make sure that the component and the model are not Same name. You may not need to use all components in each controller method to run the loaded component. In this case, you can use the Component Collection to load a Component at runtime. Inside the controller, you can perform the following operations: 1 $ this-> OneTimer = $ this-> Components-> load ('onetimer '); 2 $ this-> OneTimer-> getTime (); The component callback component also provides some request lifecycle callbacks to allow them to extend the request cycle. For more information about callback provided by components, see component API. Creating a component assumes that our online application needs to run a complex mathematical operation in different parts of the component. We can create a component to encapsulate the sharing logic used in several different controllers. The first step is the new component file and class. The created file is/app/Controller/Component/MathComponent. php. Its basic structure is as follows: 1 App: uses ('component', 'controller'); 2 class MathComponent extends Component {3 public function doComplexOperation ($ amount1, $ amount2) {4 return $ amount1 + $ amount2; 5} 6} all components of the annotation must inherit Component. Otherwise, an exception is thrown. Once the component is included in the controller, you can use the component name in the Controller's $ components array in the application controller (see the "component" section ). The Controller automatically provides a new attribute named by the component. With this attribute, we can access the component instance: 1/* generate a new component variable $ this-> Math2 and a standard $ this-> Session */3 public $ components = array ('Math ', 'session '); components defined in AppController are merged with those defined in other controllers. Therefore, you do not need to define the same component twice. When the controller contains components, you can also define a set of parameters passed to the component's constructor. These parameters are subsequently processed by the component: 1 public $ components = array (2 'Math' => array (3 'precision '=> 2, 4 'randomgenerator' => 'srand' 5), 6 'session ', 'auth '7); this Code will contain arrays of precision and randomGenerator as the second parameter passed to MathComponent ::__ construct (). According to the Conventions, any public attribute passed on the component will also have a value based on this setting. When using other components in components, sometimes one component also needs to use other components. In this case, you can use the same method as to include components in the Controller. include another component in one component-use the ''$ components' variable: 1 // app/Controller/Component/CustomComponent. php 2 App: uses ('component', 'controller '); 3 class CustomComponent extends Component {4 // the other component your component uses 5 public $ components = array ('existing'); 6 7 public function initialize (Controller $ controller) {8 $ this-> Existing-> foo (); 9} 10 11 public function bar () {12 //... 13} 14} 15 16 // app/Controller/Component/ExistingComponent. php17 App: uses ('component', 'controller'); 18 class ExistingComponent extends Component {19 20 public function foo () {21 //... 22} 23} Component API class Component base class provides several methods to delay loading other components through ComponentCollection and to handle public settings. It also provides attributes for All component callbacks. Component: :__ construct (ComponentCollection $ collection, $ settings = array () Component base class constructor. All $ settings as public attributes will also have values that match the values set in settings. The callback www.2cto. comComponent: initialize (Controller $ controller) initialize method is called before the beforeFilter method of the Controller. Component: startup (Controller $ controller) the startup method is called after the Controller's beforeFilter but before the controller executes the current action. Component: beforeRender (Controller $ controller) beforeRender method is called before the Controller renders the view and layout after the request action logic is executed. Component: The shutdown (Controller $ controller) shutdown method is called before the output is sent to the browser. Component: beforeRedirect (Controller $ controller, $ url, $ status = null, $ exit = true) beforeRedirect method is called after the Controller jump method is called and before all other methods are called. If this method returns false, the request is no longer redirected. The $ url, $ status, and $ exit variables have the same meaning for the Controller method. You can also return a string as the Redirection url or an associated array with the 'url' key. The 'Status' and 'eg' elements of this array are optional.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.