CakePHP | Using Elements for common code

Author - Rita

Problem: How to separate redundant piece of code from your view using cakephp 3.0.

Description: Let’s take an example. You have a list of products to display. We show products at many places such as

1. Show all products.

2. Show products of the specific category.

3. Show Products in the shopping cart.

4. View Single product etc.

Now the logic to show products is almost same for above features. And to replicate code to show the product at every view page is redundant.

Solution: CakePHP helps you repeat parts of your website that need to be reused. CakePHP provides a feature called Element which can be used for repeating elements. Elements exists inside app/View/Elements/ folder, and have the .ctp filename extension.

To render element inside view:

echo $this->element(“elementname”);

If your element has a name, for e.g.- productDiv.ctp, in that case the above syntax will be

echo $this->element(“productDiv”);

Where productDiv is the name of the element.

If your element has dynamic variables, for e.g. array of products, in that case you can pass data as second argument:

echo $this->element(“productDiv” , $product );

Here is an example:
1.

Above is the code structure for cakephp 3.0 or above where we have created productDiv.ctp element.

2.  Below is the code for productDiv.ctp element page:

All the rectangles in the above screenshot representing dynamic variables. We will replace them dynamically while calling the element from view.

3. View page where we are using productDiv.ctp element:

In the above screenshot , we have called our element to get product design.
So now you can use the product Div element anywhere you need without replicating code.

4.  Output:

Webner Solutions is a Software Development company focused on developing Insurance Agency Management Systems, Learning Management Systems and Salesforce apps. Contact us at dev@webners.com for your Insurance, eLearning and Salesforce applications.

Leave a Reply

Your email address will not be published. Required fields are marked *