cakephp

Page 63

Chapter 9. Components 9.1. Presentation Components are used to aid controllers in specific situations. Rather than extend Cake's core libraries, special functionality can be made into components. A guy named olle on the IRC channel once said: “ A component is a sharable little "controllerette". � We find that this is a good definition. The main goal in fact is: reusability. Components are to controllers what helpers are to views. The main difference is that components encapsulate business logic whereas helpers encapsulate presentation logic. This point actually is very important, a common confusing for new Bakers when trying to achieve reusability: I'm trying to do X, should this be a component or a helper?! Well, the answer is really simple, what does X do? Does it do business logic or presentation logic, perhaps both? If it's business logic then it's a component. If it's presentation logic then it's a helper. If it's both, then..well it's both a component and a helper. An example of the later case would be an authentification system. You would want to login, logout, restrict access, and test permissions of a user to a ressource (an action: edit, add, del.. or a url), this is business logic, so this auth system should be a component. But you also want to add some entries to the main menu when the user is logged in, and this is presentation logic.

9.2. Creating your own To create a component, add a file in app/controllers/components/ directory. Let us assume you created foo.php. Inside of the file you need to define a class that corresponds to the file name (appending the word 'Component' to the file name). So in our case you would create the following contents:

Example 9.1. A simple component

class FooComponent extends Object { var $someVar = null; var $controller = true; function startup(&$controller) { // This method takes a reference to the controller which is loading it. // Perform controller initialization here. } function doFoo() { $this->someVar = 'foo'; } }

Now, to use your component, you need to add the following code in your controller's definition:

var $components = array('Foo'); 53


Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.