Build a php – part4 framework yourself

Tram Ho

Templating

The template engine works to clean up the PHP code in View so separating the code and html makes it easier to see and maintain. Php itself is also considered to be a template enginer, but the way of writing the code and the handling it supports is not as flexible and difficult to read than other platforms. Some commonly used php templates like Laravel’s Blade, Smarty, Twig …

for example using pure php + html

for example using blade template

** Blade template **

In this article I will use the blade template used in laravel project, the document you can find here Blade Template

To create an example, we need to do the following steps

  • integrated library
  • add route
  • Add controller handle
  • add view

Integrate the library

How to integrate blade template into the project, run the following command to install the library:

User documentation, refer here https://github.com/jenssegers/blade

Add the following code to app / Dependencies.php file, the reason and the thought of adding this code, I explained in the previous parts:

Meaning of the parameters

viewPaths : The root directory contains the template

cachePath : The directory containing the cache where the template code will be rendered in plain php

Create the router

Add the following code to your routes/web.php file

Create controller

Add new app file Controllers BladeController.php

$rs = $this->blade->make('test-blade', $data)->render(); test-blade name view displayed

$data['name'] = 'world'; The variable will be passed to the view

Create display view

The created view must be created in the folder declared above

and the filename extension will be .blade.php

As the example above we will create a file in the views/test-blade.blade.php with content

{{ $name }} shows the corresponding data when passed to view $data['name'] = 'world';

Result

Here is the result

github source: https://github.com/trangianhuan/build_mvc

part 5 to continue …

Share the news now

Source : Viblo