Build your own PHP framework-the base class for abstract controllers

Source: Internet
Author: User
Tags tojson
Building your own PHP framework-the base class for abstract controllers

In the previous blog, we moved simple route parsing and execution from the portal file public/index.php into the framework. The entrance file suddenly becomes very refreshing ~ ~

However, go to our controller and see the following code:

     Public function Actionview ()    {        $body = ' Test body information ';         require '.. /views/site/view.php ';    }

Should we write an action to render the page, we have to find the view of the corresponding path, and then require it in. Certainly not, so we have to abstract a controller base class, implement a method of rendering the page, let other controllers inherit, you can use the corresponding method.

Needless to say, the base class of this controller must be written in the framework. and also to write two, one placed in base, one placed in the Web, the controller in the web inherits from base.

First look at the base of the

 
  Phpnamespace sf\base; /*  */class  controller{}

There is only one empty class waiting for the content to be added.

Then look at the Web

 Phpnamespace Sf\web;/** Controller is the base class for classes containing Controller logic. * @author Harry Sun <[email protected]> ; */classControllerextends\sf\base\controller{/** * Renders a view * @param string $view the view name.     * @param array $params The parameters (Name-value pairs) that should is made available in the view. */     Public functionRender$view,$params= [])    {        Extract($params); return require'.. /views/'.$view. '. php '; }}

As you can see, we first import the variables into the current symbol table from the array, and then introduce the corresponding view page.

And then, in Sitecontroller, we just need to write that.

 
  Phpnamespace app\controllers;  Use Sf\web\controller; class extends controller{    publicfunction  actiontest ()    {        echo ' Success! ' ;    }      Public function Actionview ()    {        $this->render (' Site/view ', [' body ' = ' Test body information ']);}    }

Then, visit Http://localhost/simple-framework/public/index.php?r=site/view and you'll see the same page as before.

Let's refine the controller in base.

 Phpnamespace sf\base;/** Controller is the base class for classes containing Controller logic. * @author Harry Sun <[email protected]> ; */classcontroller{/** * @var string The ID of this controller. */     Public $id; /** * @var action The action is currently being executed. */     Public $action;}

Two attributes were added to record the current controller and action.

Then, after parsing the router, we assign it a value, code as follows:

 Phpnamespace Sf\web;/** * application is the base class for all application classes. * @author Harry Sun <[email protected]>*/classApplicationextends\sf\base\application{/** * Handles the specified request. * @return Response the resulting Response*/     Public functionHandleRequest () {$router=$_get[' R ']; List($controllerName,$actionName) =Explode('/',$router); $ucController=Ucfirst($controllerName); $controllerNameAll=$this->controllernamespace. '\\' .$ucController. ' Controller '; $controller=New $controllerNameAll(); $controller->id =$controllerName; $controller->action =$actionName; return Call_user_func([$controller, ' action '.Ucfirst($actionName)]); }}

Then we can get the controller name and action name in the controller and view, and modify the view.php as follows:

<HTML>    <Head>        <title>Title
  title>    <Head>    <Body>        
   php echo $this->id;?><BR/>         
      php echo $this->action; ?> < BR />  
       php echo $body; ?>  
        body> 
         html>   
       
         

And then we can see the following page.

Some people think that now everyone is separated, we do not need to use PHP to render a page, just need to return a josn string is good, this is more simple, in the Web controller to add a Tojson method can be

    /* *     Convert a array to JSON string     * @param string $data     *     /Public function ToJson ($data)    {        if (is_string($data ) {            return$data;        }         return json_encode ($data);    }

To change the actiontest in Sitecontroller, modify the following:

     Public function actiontest ()    {        $data = [' first ' = ' awesome-php-zh_cn ', ' second ' = ' simple-framework '];         Echo $this->tojson ($data);    }

By accessing Http://localhost/simple-framework/public/index.php?r=site/view, you can see the corresponding JSON string.

All right, let's get here today. Project content and blog content will also be put on GitHub, welcome suggestions.

code:https://github.com/craryprimitiveman/simple-framework/tree/0.3

Blog Project:https://github.com/craryprimitiveman/create-your-own-php-framework

  • 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.