[CakePHP]: How to build a new helper in cakephp


Posted on 2015-11-26 15:51:11


Suppose, you have a random string constructor, you want to use this content in any where in the view, you can write this function in a controller that then userequestAction to call out. But this is not good way, not to mention the use of multiple requestAction would make the application slower. We will solve this problem by building a helper! Can understand na that helper in CakePHP is a collection of useful libraries for use in view. CakePHP has built a lot of helper: form, html, ajax, number, session, rss, xml, time ....
 helper
To use the helper does the Controller must be declared through the variable $ helpers Examples:
You can learn about the cake's helper is available by visiting: cake / libs / view / helpersAnd now, we started to write a helper for themselves! Suppose I want to write a helper named: Common => filename respectivelycommon.php Set in app / views / helpers /
cake helper 02 [CakePHP]: How to build a helper
Note that AppHelper is the base class for all Helper .Therefore so when creating a new helper, you may e xtends from AppHelper or from a certain Helper available on CakePHP.

Helper helper class name = name + "helper"

Beginning with the class Helper Common name , placed in the directory (app / views / helpers / common.php) With random string constructor 1 .

Usage class Common Herpler just created:

- I create 1 Controller name Testcommons (app / controllers / testcommons _controller.php) to use the newly created class Helper Common
– Use view : Create file test_helper.ctp (app/views/testcommons/ test_helper.ctp) Chạy thử : http://localhost/cakephp/testcommons/test_helper
cake helper 03 [CakePHP]: How to build a helper
Note: The variable $ helpers are declared in controllers are only available in the View of the controller. If I declare in the controller NewsController it into Product page, use echo $ common-> create_random_string (6); will get an error immediately! Thus inapplicable nature "used anytime, anywhere". But it's okay, we can solve this problem by: - Creating file app_controller.php placed in the app directory, the contents of this file are as follows :
cake helper 04 [CakePHP]: How to build a helper Everything put in AppController will work on all other controllers, so we just declare