CakePHP2.xCookBook Chapter 5 controller components

Source: Internet
Author: User
The 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 components of this array

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)
  • Sessions (session)
  • Access control lists (Access control list)
  • Emails (email)
  • Cookies
  • Authentication (permission verification)
  • Request handling)
  • Pagination)

The details 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.

Configuration component

Some core components need to be configured. The components to be configured includeAuthorization,CookieAndEmail component. 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 'authorize' => array('controller'), 5 'loginAction' => array('controller' => 'users', 'action' => 'login') 6 ), 7 'Cookie' => 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 example above can also be expressed:

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 should be set before the beforeFilter () operation of the controller. 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 related documents to determine the configuration options provided by 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.php 11 App::uses('AuthComponent', 'Controller/Component'); 12 class MyAuthComponent extends AuthComponent { 13 // Add your code to override the core AuthComponent 14 }

In the controller of the previous example, the alias $ this-> Auth is MyAuthComponent.

Annotation

Aliases must be used for any component with aliases, including references to other components.

Use 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', 'Cookie'); 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 and component added to the controller share the same 'namespace 'as the attribute identity, you need to ensure that the component and model are not named the same.

Run the loaded component

You may not need all components to be available in every controller method. In this case, you can useComponent CollectionLoad a component. In the controller, you can perform the following operations:

1 $this->OneTimer = $this->Components->load('OneTimer'); 2 $this->OneTimer->getTime();

Component callback

The component also provides some request lifecycle callbacks to allow them to extend the request cycle. For more information about the callback provided by the component, seeComponent API.

Create component

Assume that our online application needs to run a complex mathematical operation in different parts of it. 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 }

Annotation

All components must inherit Component. Otherwise, an exception is thrown.

Include components in the controller

Once the component is complete, you can use it in the application controller by placing the component name in the controller's $ components array (see the "components" 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-> Math 2 and a standard $ this-> Session */3 public $ components = array ('math ', 'session ');

Components defined in AppController are merged with those 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 include 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.

Use other components in components

Sometimes other components are required for a component. 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.php 17 App::uses('Component', 'Controller'); 18 class ExistingComponent extends Component { 19 20 public function foo() { 21 // ... 22  } 23 }

Component API

Class Component

The component base class provides several methods for delaying loading other components through ComponentCollection and processing 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.

Callback Component: initialize ( Controller $ controller)

The initialize method is called before the beforeFilter method of the controller.

Component: startup ( Controller $ controller)

The startup method is called after the beforeFilter of the controller but before the controller executes the current action.

Component: beforeRender ( Controller $ controller)

The beforeRender method is called before the controller renders the view and layout after the request action logic is executed.

Component: shutdown ( Controller $ controller)

The shutdown method is called before the output is sent to the browser.

Component: beforeRedirect ( Controller $ controller, $ Url, $ Status = null, $ Exit = true)

The 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.