这篇文章主要介绍了thinkPHP3.2.2框架行为扩展,结合实例形式分析了thinkPHP3.2.2框架行为扩展原理、实现方法及相关操作注意事项,需要的朋友可以参考下
本文实例讲述了thinkPHP3.2.2框架行为扩展。分享给大家供大家参考,具体如下:
首先介绍一下行为扩展类,本人愚钝,还是借用tp手册上的来说:
行为(Behavior)是一个比较抽象的概念,你可以想象成在应用执行过程中的一个动作或者处理,在框架的执行流程中,各个位置都可以有行为产生,例如路由检测是一个行为,静态缓存是一个行为,用户权限检测也是行为,大到业务逻辑,小到浏览器检测、多语言检测等等都可以当做是一个行为,甚至说你希望给你的网站用户的第一次访问弹出Hello,world!这些都可以看成是一种行为,行为的存在让你无需改动框架和应用,而在外围通过扩展或者配置来改变或者增加一些功能。
而不同的行为之间也具有位置共同性,比如,有些行为的作用位置都是在应用执行前,有些行为都是在模板输出之后,我们把这些行为发生作用的位置称之为标签(位),当应用程序运行到这个标签的时候,就会被拦截下来,统一执行相关的行为,类似于AOP编程中的“切面”的概念,给某一个切面绑定相关行为就成了一种类AOP编程的思想。
那下面就入正题,讲解一下行为(Behavior)的实例
让行为工作有两种方式:
1.通过在conf目录下的tags.php文件 配置行为 通过\Think\Hook::listen(name);触发行为
2.通过\Think\Hook::add(name,class_namespace) 注册一个行为,然后触发(注册函数必须在触发函数之前)
在我们讲解实例之前,很有必要先讲讲行为是怎么触发的。
行为触发靠的是\Think\Hook::listen(name)方法,那方法里面到底做了什么,我们先看看源码:
/**
* 监听标签的插件
* @param string $tag 标签名称
* @param mixed $params 传入参数
* @return void
*/
/**
* add by yangligao 2014/8/25
* listen 个人觉得方法名称取得不怎么好理解,看程序中就知道这个方法实际上就是看$tags中有没有参数中的tag
* 如果有,就触发之;
* 如果没有,你懂的,过之(至少程序中是没有做操作)。
*/
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) {
// 如果返回false 则中断插件执行
return ;
}
}
if(APP_DEBUG) { // 记录行为的执行日志
trace('[ '.$tag.' ] --END-- [ RunTime:'.G($tag.'Start',$tag.'End',6).'s ]','','INFO');
}
}
// return; //thinkphp原始的样式
return $result;//笔者^_^自己添加的
}
这个方法里面记录行为的一些运行状态的值,函数最后一点笔者做了一点修改,只是让这个方法有了一份返回值(而非返回空)
最重要的地方就是
$result = self::exec($name, $tag,$params);
这个地方就开始执行所谓的行为了,先看看exec方法的源码
/**
* 执行某个插件
* @param string $name 插件名称
* @param string $tag 方法名(标签名)
* @param Mixed $params 传入的参数
* @return void
*/
/**
* add by yangligao 2014/8/25
* exec 执行文件
*/
static public function exec($name, $tag,&$params=NULL) {
if('Behavior' == substr($name,-8) ){
// 行为扩展必须用run入口方法
$tag = 'run';
}
// file_put_contents('D:/1.txt',$name,FILE_APPEND );
$addon = new $name();
return $addon->$tag($params);
}
这个方法所做的就是先判断行为配置中的设定的类名中是否有Behavior这个字符串,如果有就执行一个叫run的方法
准备工作差不多了。下面动手试试实例
方法一:通过在conf目录下的tags.php文件 配置行为 通过\Think\Hook::listen(name);触发行为
我们先在Home/Conf下面准备tags.php配置文件
<?php return array( 'app_app' => array('Home\Behavior\DemoShowHelloWorldBehavior'), );
根据这个配置文件,我们还得在Home/Behavior下面准备DemoShowHelloWorldBehavior的类文件
<?php
namespace Home\Behavior;
use Think\Controller;
/**
* 这个文件的类可以继承Controller类 这样就可以使用assign方法
* 这个方法框架里面:对你的返回值不理睬,只是用作判断插件有没有出错
* 出于某个目的,笔者对Hook::listen方法作了小修改 让他可以返回值,或许会有点用
*/
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;
}
}
这个类文件,我们是继承的控制器,里面做了两件事:
1.返回一个字符串
2.使用Controller方法的assign方法给模板赋值
然后我们来触发这个行为,你只需要在控制器总写上一下代码以及在对应模板中输出对应变量
$behaviorReturn = \Think\Hook::listen('app_app');
<p>{$behavior_assign}</p>
这样页面就会输出行为类中assign的变量值了,行为类的返回值这里没有打印,你有兴趣可以打印看看哦
方法二:.通过\Think\Hook::add(name,class_namespace) 注册一个行为,然后触发(注册函数必须在触发函数之前)
这个与方法一唯一的区别就是他不用定义tags.php文件,取而代之的是一个php语句(如下):
\Think\Hook::add('app_app', 'Home\\Behavior\\DemoShowHelloWorldBehavior');
其他的操作都相同。
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注PHP中文网!
相关推荐:
The above is the detailed content of Analysis of thinkPHP3.2.2 framework behavior extension and demo. For more information, please follow other related articles on the PHP Chinese website!
PHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AMPHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.
PHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AMPHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.
Choosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AMPHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.
PHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AMPHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.
PHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AMPHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip
How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AMPHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.
How does PHP handle object cloning (clone keyword) and the __clone magic method?Apr 17, 2025 am 12:24 AMIn PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.
PHP vs. Python: Use Cases and ApplicationsApr 17, 2025 am 12:23 AMPHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment






