thinkPHP 3.2. 2 Framework Behavior Extensions and demo Examples

  • 2021-10-24 19:12:49
  • OfStack

This article illustrates the behavior extension of thinkPHP 3.2. 2 framework. Share it for your reference, as follows:

First of all, introduce 1 behavior extension class, I am stupid, or borrow tp manual:

Behavior (Behavior) is a relatively abstract concept, You can think of it as an action or process during the execution of the application. In the execution process of the framework, there can be behaviors in various positions, such as routing detection is a behavior, static cache is a behavior, and user rights detection is also a behavior, ranging from business logic to browser detection, multilingual detection, etc., which can be regarded as a behavior, even saying that you want to pop up Hello and world for the first visit of your website users! These can be seen as a kind of behavior, the existence of behavior allows you to change or add 1 function in the periphery through extension or configuration without changing the framework and application.

And different behaviors also have commonality in position, For example, some behaviors work before the application is executed. Some behaviors are after the template is output, and we call the position where these behaviors work tags (bits). When the application program runs to this tag, it will be intercepted, and all 1 executes related behaviors, which is similar to the concept of "section" in AOP programming. Binding related behaviors to a certain section becomes the idea of AOP programming.

Let's get down to business and explain the example of behavior 1 (Behavior)

There are two ways to make behavior work:

1. Configure the behavior through the tags. php file in the conf directory \Think\Hook::listen(name); Triggering behavior

2. Adoption \Think\Hook::add(name,class_namespace) Register a behavior and trigger it (register the function before triggering the function)

Before we explain the examples, it is necessary to talk about how the behavior is triggered.

Behavior triggers by \Think\Hook::listen(name) Method, what is done in that method, let's look at the source code first:


/**
 *  Plug-ins for listening tags 
 * @param string $tag  Label name 
 * @param mixed $params  Pass in parameters 
 * @return void
 */
/**
 * add by yangligao 2014/8/25
 * listen  Personally, I think the name of the method is not easy to understand. Look at the program and know that this method is actually looking at it $tags Is there a parameter in the tag
 *    If so, trigger it; 
 *    If not, you know, pass it ( At least there is no operation in the program ) . 
 */
static public function listen($tag, &$params=NULL) {
 if(isset(self::$tags[$tag])) {
  if(APP_DEBUG) {
   G($tag.'Start');
   trace('[ '.$tag.' ] --START--','','INFO');
  }
  foreach (self::$tags[$tag] as $name) {
   APP_DEBUG && G($name.'_start');
   $result = self::exec($name, $tag,$params);
   if(APP_DEBUG){
    G($name.'_end');
    trace('Run '.$name.' [ RunTime:'.G($name.'_start',$name.'_end',6).'s ]','','INFO');
   }
   if(false === $result) {
    //  If you return false  The plug-in execution is interrupted 
    return ;
   }
  }
  if(APP_DEBUG) { //  Record the execution log of the behavior 
   trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO');
  }
 }
 // return; //thinkphp Original style 
 return $result;// Author ^_^ Added by oneself 
}

This method records the values of 1 running state of the behavior, and the last 1 point of the function has been modified by the author, only to make this method have a return value (instead of returning null)

The most important thing is that


$result = self::exec($name, $tag,$params);

This place began to perform the so-called behavior. Let's take a look first exec The source code of the method


 /**
  *  Execute a plug-in 
  * @param string $name  Plug-in name 
  * @param string $tag  Method name (label name) 
  * @param Mixed $params  Parameters passed in 
  * @return void
  */
 /**
  * add by yangligao 2014/8/25
  * exec  Execution file 
  */
 static public function exec($name, $tag,&$params=NULL) {
  if('Behavior' == substr($name,-8) ){
   //  Behavior extension must be used with run Entry method 
   $tag = 'run';
  }
//  file_put_contents('D:/1.txt',$name,FILE_APPEND );
  $addon = new $name();
  return $addon->$tag($params);
 }

What this method does is to determine whether there is the string Behavior in the class name set in the behavior configuration, and if so, execute a method called run

The preparations are almost done. Let's try an example

Method 1: Configure the behavior through the tags. php file in the conf directory \Think\Hook::listen(name); Triggering behavior

We first prepare the tags. php configuration file under Home/Conf


<?php
return array(
  'app_app' => array('Home\Behavior\DemoShowHelloWorldBehavior'),
);

According to this configuration file, we have to prepare under Home/Behavior DemoShowHelloWorldBehavior Class file of


<?php
namespace Home\Behavior;
use Think\Controller;
/**
 *  The class of this file can inherit Controller Class   So you can use the assign Method 
 *  Inside this method framework: Ignore your return value, just use it to judge whether there is an error in the plug-in 
 *  For a certain purpose, the author is interested in Hook::listen The method has been slightly modified   Let him return a value, which may be of some use 
 */
class DemoShowHelloWorldBehavior extends Controller{
 public function run(){
  $return_string = '(Home\Behavior)<font>DemoShowHelloWoldBehavior</font> is Running....^_^!<hr>';
  $this->assign('behavior_assign','This is assigned by <font>DemoShowHelloWoldBehavior</font>');
  return $return_string;
 }
}

This class file, we are the inherited controller, does two things in it:

1. Returns a string

2. Assign values to templates using the assign method of the Controller method

Then let's trigger this behavior. You only need to write 1 code in the controller and output the corresponding variable in the corresponding template


$behaviorReturn = \Think\Hook::listen('app_app');


<div>{$behavior_assign}</div>

In this way, the page will output the variable value of assign in the behavior class. The return value of the behavior class is not printed here. You can print it if you are interested.

Method 2:. Pass \Think\Hook::add(name,class_namespace) Register a behavior and trigger it (register the function before triggering the function)

This differs from Method 1 only 1 in that instead of defining the tags. php file, it uses an php statement (as follows):


\Think\Hook::add('app_app', 'Home\\Behavior\\DemoShowHelloWorldBehavior');

All other operations are the same.

For more readers interested in thinkPHP related contents, please check the topics of this site: "ThinkPHP Introduction Tutorial", "thinkPHP Template Operation Skills Summary", "ThinkPHP Common Methods Summary", "codeigniter Introduction Tutorial", "CI (CodeIgniter) Framework Advanced Tutorial", "Zend FrameWork Framework Introduction Tutorial" and "PHP Template Technology Summary".

Hope that this article is based on ThinkPHP framework of PHP programming help.


Related articles: