Use Composer to perfect your PHP framework (i)--View loading

Source: Internet
Author: User
Tags autoload php framework

For this tutorial sample code see Https://github.com/johnlui/My-First-Framework-based-on-Composer

Review

After a series of tutorials, "using Composer to build your own PHP framework," We have built a framework MFFC with routing, MVC architecture, and ORM capabilities. Next we continue to refine the project.

Let's start with the view loading, which is currently the most uncomfortable place. We'll encapsulate a view load class, let it load the view, and pass the variables into the view. This class will only expose a few simple interfaces, let us in the controller with the cool, let us write code while laughing. Really laugh, laugh aloud. :-D

Body Concept

The work of the view load class is actually very simple:

1. Find view file According to view name, Support folder

2. More convenient, more elegant to pass the value of the variable into the view

In this article we will not introduce the template engine, only the ability to load files and pass variables.

Basic Preparation

We're going to introduce the view loader, which formally opens up the assembly door, so we need to do some preparatory work.

Start Process component

Separate the code inside the public/index.php into the initiator (bootstrap) and create a new mffc/bootstrap.php file:

<?phpuse Illuminate\database\capsule\manager as capsule;//definition base_pathdefine (' Base_path ', __DIR__);//Autoload Automatically load require base_path. ' /vendor/autoload.php ';//eloquent orm$capsule = new capsule; $capsule->addconnection (Require Base_path. ' /config/database.php '); $capsule->booteloquent ();

Modify the public/index.php to:

<?php//definition public_pathdefine (' Public_path ', __dir__);//launcher require public_path. ' /.. /bootstrap.php ';//routing configuration, starting processing require base_path. ' /config/routes.php ';

At this point we completed the separation of the portal file and the initiator, and defined two global constants Base_path and Public_path.

Here we need to pay special attention: "Introduce routing profile" This step is not simply introduced a configuration file, the last line of the routing file Macaw::d ispatch (); is where a function in a controller is actually executed, all readiness conditions should be done before loading the routing file, such as eloquent initialization, initialization of the Composer package we will use later, and so on.

Introduce error page hint component

We chose Filp/whoops as our error hint component package.

Modify Composer.json:

"Require": {  "Codingbean/macaw": "Dev-master",  "illuminate/database": "*",  "Filp/whoops": "*"},

Run composer Update, and then add it at the end of bootstrap.php:

Whoops error hint $whoops = new \whoops\run; $whoops->pushhandler (new \whoops\handler\prettypagehandler); $whoops Register ();

To refresh the http://127.0.0.1:81, you should still get this page:

Below we will add an error page with no matches in the routing configuration and modify the config/routes.php:

<?phpuse Noahbuscher\macaw\macaw; Macaw::get (', ' [email protected] '); Macaw::get (' Fuck ', function () {  echo "succeeded!) ";}); Macaw:: $error _callback = function () {  throw new Exception ("Route no match 404 Not Found");}; Macaw::d ispatch ();

Now to access a randomly entered URL, such as HTTP://127.0.0.1:81/ASD, we will see the following screen:

is not a very familiar feeling!

Unfortunately, this error hint packet is the one that Laravel used, so our lovely MFFC framework became a Laravel after growing up. %>_<%

Implementing loaders

Upon completion of the foundation preparation, we formally began manufacturing the view loader.

The view loader is a pluggable component, and we should put all the pluggable components in one place, and we recommend placing them under Mffc/services in MFFC.

The Base Component library provided by the CI framework is called helpers, and Laravel uses the Illuminate/support package to provide some reusable system functions. In fact, "Illuminate/support" This package has been our ORM package "Illuminate/database" relies on, now MFFC framework can be directly used. , the Chinese document of this package see: http://laravel-china.org/docs/helpers

There are two reasons why we do not place the view loader at the core of the system as the CI framework does:

    1. More resource-efficient calls based on namespaces and automatic loading
    2. In the era of mobile internet and big front-end, the backend is becoming more and more API and JSON. Many times there is no view, no need to increase the fearless consumption.

Here's the start of implementing the view loader.

Create a new Mffc/services folder and modify Composer.json to automatically classify all classes under this folder into the root namespace:

"AutoLoad": {  "Classmap": [    "App/controllers",    "App/models",    "Services"  ]}

Create a new services/view.php file with the following contents:

<?php/*** \view*/class view{Const View_base_path = '/app/views/';  Public $view;  Public $data;  Public function __construct ($view) {$this->view = $view; public static function make ($viewName = null) {if (! $viewName) {throw new InvalidArgumentException ("View name not Can be empty!    ");      } else {$viewFilePath = Self::getfilepath ($viewName);      if (Is_file ($viewFilePath)) {return new View ($viewFilePath); } else {throw new unexpectedvalueexception ("View file does not exist!)      ");    }}} public function with ($key, $value = null) {$this->data[$key] = $value;  return $this;    } private static function GetFilePath ($viewName) {$filePath = Str_replace ('. ', '/', $viewName); Return Base_path.self::view_base_path. $filePath.  PHP '; The Public Function __call ($method, $parameters) {if (Starts_with ($method, ' with ')) {return $this->with (SN    Ake_case (substr ($method, 4)), $parameters [0]); } throw new Badmethodcallexception ("method [$method] does not exist!. ");}} 

Run composer Dump-autoload, we can call this class directly in the controller when we are done.

Modify controllers/homecontroller.php:

<?php/*** \homecontroller*/class HomeController extends basecontroller{public    function Home ()  {    $ This->view = View::make (' home ')->with (' article ', Article::first ())                                    ->withtitle (' MFFC:-D ')                                    Withfuckme (' ok! ');}  }

Modify controllers/basecontroller.php:

<?php/*** \basecontroller*/class basecontroller{  protected $view;    Public function __construct ()  {  } public  function __destruct ()  {    $view = $this->view;    if ($view instanceof view) {      extract ($view->data);      Require $view->view;    }}}  

Modify app/views/home.php:

<! DOCTYPE html>

Refresh, you will see the following pages:

The view loader implementation is now complete. Let me say a little bit about the basic idea of designing the View loader:
    1. This view loader class mimics the view class of Laravel, which implements a static method make, which accepts the view name as a parameter. As the delimiter for the directory.
    2. The Make static method checks whether the view name is empty, checks whether the view file exists, and gives the appropriate exception. This is why we introduced the exception handling package.
    3. When the view name is valid and the file exists, instantiate an object of the view class and return.
    4. Use the WITH (' key ', $value) or elegant Withkey ($value) to insert the variable that you want to call in the View object. Withfuckme ($value) is transformed into $fuck _me for view use using the Serpentine nomenclature.
    5. The final assembled View object is assigned to the HomeController member variable $view, which is inherited from the Basecontroller.
    6. The destructor __destruct () in the parent class Basecontroller will handle this member variable after the function home () execution completes: Extract the variable that the view is going to use, require the view file, and sends the result of the final operation to Browser, Process end.

Use Composer to perfect your PHP framework (i)--View loading

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.