Home Database Mysql Tutorial ThinkPHP3.2 扩展

ThinkPHP3.2 扩展

Jun 07, 2016 pm 03:43 PM
thinkphp3.2 Expand

之前写到TP3.1的行为扩展是tag();在TP3.2中引入了另一种说法—:钩子。 我们来看一下TP3.2中的钩子这个东西: 一:文件流程: 1:/index.php - require './ThinkPHP/ThinkPHP.php'; 2:/ThinkPHP/ThinkPHP.php—- require CORE_PATH.'Think'.EXT; Think\Think:

之前写到TP3.1的行为扩展是tag();在TP3.2中引入了另一种说法—:钩子。
我们来看一下TP3.2中的钩子这个东西:
一:文件流程:
1:/index.php ->require './ThinkPHP/ThinkPHP.php';
2:/ThinkPHP/ThinkPHP.php—->require CORE_PATH.'Think'.EXT; Think\Think::start();
3:/ThinkPHP/Library/Think/Think.class.php—–>App::run();
4:/ThinkPHP/Library/Think/App.class.php 。到这里基本流程就走完了,(这里不说细节);

二:代码:
1:看一下 App::run()方法:

<code>        
        Hook<span>::listen(<span>'app_init'</span>);</span>
        App<span>::init();</span>
        
        Hook<span>::listen(<span>'app_begin'</span>);</span>
        <span>// Session初始化</span>
        <span>if(!IS_CLI)</span>{
            <span>session(<span>C(<span>'SESSION_OPTIONS'</span>)</span>)</span>;
        }
        <span>// 记录应用初始化时间</span>
        <span>G(<span>'initTime'</span>)</span>;
        App<span>::exec();</span>
        
        Hook<span>::listen(<span>'app_end'</span>);</span>
        return ;</code>
Copy after login

其中的Hook::listen(”)就是用来执行钩子的,我们可以在app_init这个安插的位置用来获取应用中安装的插件。

看一下Hook::listen();

<code><span><span> @param</span><span> @param</span> mixed $params 传入参数
     *<span> @return</span> void
     */</span>
    <span>static</span> <span>public</span> <span><span>function</span> <span>listen</span><span>(<span>$tag</span>, &<span>$params</span>=NULL)</span> {</span>
        <span>if</span>(<span>isset</span>(<span>self</span>::<span>$tags</span>[<span>$tag</span>])) {
            <span>if</span>(APP_DEBUG) {
                G(<span>$tag</span>.<span>'Start'</span>);
                trace(<span>'[ '</span>.<span>$tag</span>.<span>' ] --START--'</span>,<span>''</span>,<span>'INFO'</span>);
            }
            <span>foreach</span> (<span>self</span>::<span>$tags</span>[<span>$tag</span>] <span>as</span> <span>$name</span>) {
                APP_DEBUG && G(<span>$name</span>.<span>'_start'</span>);
                <span>$result</span> =   <span>self</span>::exec(<span>$name</span>, <span>$tag</span>,<span>$params</span>);
                <span>if</span>(APP_DEBUG){
                    G(<span>$name</span>.<span>'_end'</span>);
                    trace(<span>'Run '</span>.<span>$name</span>.<span>' [ RunTime:'</span>.G(<span>$name</span>.<span>'_start'</span>,<span>$name</span>.<span>'_end'</span>,<span>6</span>).<span>'s ]'</span>,<span>''</span>,<span>'INFO'</span>);
                }
                <span>if</span>(<span>false</span> === <span>$result</span>) {
                    <span>// 如果返回false 则中断插件执行</span>
                    <span>return</span> ;
                }
            }
            <span>if</span>(APP_DEBUG) { <span>// 记录行为的执行日志</span>
                trace(<span>'[ '</span>.<span>$tag</span>.<span>' ] --END-- [ RunTime:'</span>.G(<span>$tag</span>.<span>'Start'</span>,<span>$tag</span>.<span>'End'</span>,<span>6</span>).<span>'s ]'</span>,<span>''</span>,<span>'INFO'</span>);
            }
        }
        <span>return</span>;
    }</code>
Copy after login

其中关键是:self::exec($name, $tag,$params); 看一下exec的代码:

<code> <span>/**
     * 执行某个插件
     *<span> @param</span> string $name 插件名称
     *<span> @param</span><span> @param</span> Mixed $params 传入的参数
     *<span> @return</span> void
     */</span>
    <span>static</span> <span>public</span> <span><span>function</span> <span>exec</span><span>(<span>$name</span>, <span>$tag</span>,&<span>$params</span>=NULL)</span> {</span>
        <span>if</span>(<span>false</span> === strpos(<span>$name</span>,<span>'\\'</span>)) {
            <span>// 插件(多个入口)</span>
            <span>$class</span>   =  <span>"Addons\\{$name}\\{$name}Addon"</span>;
        }<span>else</span>{
            <span>// 行为扩展(只有一个run入口方法)</span>
            <span>$class</span>   =  <span>$name</span>.<span>'Behavior'</span>;
            <span>$tag</span>    =   <span>'run'</span>;
        }
        <span>$addon</span>   = <span>new</span> <span>$class</span>();
        <span>return</span> <span>$addon</span>-><span>$tag</span>(<span>$params</span>);
    }</code>
Copy after login

最后还不是 new $class();进而return $addon->$tag($params); 又转到了具体钩子的代码方法。其实就是我们原本的调用class的方法,只不过经过别人的高度封装了。

三:那么问题来了,这个钩子有什么用呢? 怎么用?
这里以OneThink 的{:hook('AdminIndex')}为例,看一些别人是怎么用的。
在系统初始化到 Hook::listen('app_init'); 时,

<code><span><span><?php </span>
<span>return</span> <span>array</span>(
    <span>'app_init'</span>=><span>array</span>(<span>'Common\Behavior\InitHook'</span>)
);</span></span></code>
Copy after login

一看就明白,无非就是读取持久化的信息,放到缓存或是其他的方式

<code> <span>// 行为扩展的执行入口必须是run</span>
    <span>public</span> <span><span>function</span> <span>run</span><span>(&<span>$content</span>)</span>{</span>
        <span>if</span>(<span>isset</span>(<span>$_GET</span>[<span>'m'</span>]) && <span>$_GET</span>[<span>'m'</span>] === <span>'Install'</span>) <span>return</span>;

        <span>$data</span> = S(<span>'hooks'</span>);
        <span>if</span>(!<span>$data</span>){
            <span>$hooks</span> = M(<span>'Hooks'</span>)->getField(<span>'name,addons'</span>);
            <span>foreach</span> (<span>$hooks</span> <span>as</span> <span>$key</span> => <span>$value</span>) {
                <span>if</span>(<span>$value</span>){
                    <span>$map</span>[<span>'status'</span>]  =   <span>1</span>;
                    <span>$names</span>          =   explode(<span>','</span>,<span>$value</span>);
                    <span>$map</span>[<span>'name'</span>]    =   <span>array</span>(<span>'IN'</span>,<span>$names</span>);
                    <span>$data</span> = M(<span>'Addons'</span>)->where(<span>$map</span>)->getField(<span>'id,name'</span>);
                    <span>if</span>(<span>$data</span>){
                        <span>$addons</span> = array_intersect(<span>$names</span>, <span>$data</span>);
                        Hook::add(<span>$key</span>,<span>$addons</span>);
                    }
                }
            }
            S(<span>'hooks'</span>,Hook::get());
        }<span>else</span>{
            Hook::import(<span>$data</span>,<span>false</span>);
        }
    }</code>
Copy after login

当在程序执行到{:hook(‘AdminIndex’)}时—>调用的是Hook::listen(‘AdminIndex’);
AdminIndex这个挂载点包含了三个插件:分别是:SiteStat, SystemInfo,DevTeam。
用一个循环来分别按顺序执行.

总结:钩子其实就是起到一个挂载点的作用,这个钩子挂在哪里,就可以在哪里执行,内容或功能就是挂载插件或类库的具体实现。这样实现的代码就有很大的灵活性,挂载点不变,挂的东西变量,功能也就相应的变化,是不是很灵活强大呀。


以上只属于学习笔记,若有错请指正。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use PHP's SNMP extension? How to use PHP's SNMP extension? Jun 02, 2023 am 10:22 AM

The SNMP extension for PHP is an extension that enables PHP to communicate with network devices through the SNMP protocol. Using this extension, you can easily obtain and modify the configuration information of network devices, such as CPU, memory, network interface and other information of routers, switches, etc. You can also perform control operations such as switching device ports. This article will introduce the basic knowledge of the SNMP protocol, how to install the SNMP extension of PHP, and how to use the SNMP extension in PHP to monitor and control network devices. 1. SN

Extensions and third-party modules for PHP functions Extensions and third-party modules for PHP functions Apr 13, 2024 pm 02:12 PM

To extend PHP function functionality, you can use extensions and third-party modules. Extensions provide additional functions and classes that can be installed and enabled through the pecl package manager. Third-party modules provide specific functionality and can be installed through the Composer package manager. Practical examples include using extensions to parse complex JSON data and using modules to validate data.

From start to finish: How to use php extension cURL to make HTTP requests From start to finish: How to use php extension cURL to make HTTP requests Jul 29, 2023 pm 05:07 PM

From start to finish: How to use php extension cURL for HTTP requests Introduction: In web development, it is often necessary to communicate with third-party APIs or other remote servers. Using cURL to make HTTP requests is a common and powerful way. This article will introduce how to use PHP to extend cURL to perform HTTP requests, and provide some practical code examples. 1. Preparation First, make sure that php has the cURL extension installed. You can execute php-m|grepcurl on the command line to check

How to install mbstring extension under CENTOS7? How to install mbstring extension under CENTOS7? Jan 06, 2024 pm 09:59 PM

1.UncaughtError:Calltoundefinedfunctionmb_strlen(); When the above error occurs, it means that we have not installed the mbstring extension; 2. Enter the PHP installation directory cd/temp001/php-7.1.0/ext/mbstring 3. Start phpize(/usr/local/bin /phpize or /usr/local/php7-abel001/bin/phpize) command to install php extension 4../configure--with-php-config=/usr/local/php7-abel

How to use the Aurora Push extension to implement batch message push function in PHP applications How to use the Aurora Push extension to implement batch message push function in PHP applications Jul 25, 2023 pm 08:07 PM

How to use the Aurora Push extension to implement batch message push function in PHP applications. In the development of mobile applications, message push is a very important function. Jiguang Push is a commonly used message push service that provides rich functions and interfaces. This article will introduce how to use the Aurora Push extension to implement batch message push functionality in PHP applications. Step 1: Register a Jiguang Push account and obtain an API key. First, we need to register on the Jiguang Push official website (https://www.jiguang.cn/push)

How to use PHP's ZipArchive extension? How to use PHP's ZipArchive extension? Jun 02, 2023 am 08:13 AM

PHP is a popular server-side language that can be used to develop web applications and process files. The ZipArchive extension for PHP is a powerful tool for manipulating zip files in PHP. In this article, we’ll cover how to use PHP’s ZipArchive extension to create, read, and modify zip files. 1. Install the ZipArchive extension. Before using the ZipArchive extension, you need to ensure that the extension has been installed. The installation method is as follows: 1. Install

Reasons and solutions why D drive cannot be expanded in win11 system Reasons and solutions why D drive cannot be expanded in win11 system Jan 08, 2024 pm 12:30 PM

Some users feel that their d drive space is not enough and want to expand the d drive space. However, during the operation, they find that their win11d drive cannot be expanded and the extended volume is gray. In fact, this may be due to insufficient disk space. Let’s take a look at the solutions below. Why the win11d disk cannot be expanded: 1. Insufficient space 1. First of all, to expand the d disk, you need to ensure that your disk has "available space", as shown in the figure. 2. If there is no available space like this, then there is naturally no way to expand. 3. If you want to expand the D drive at this time, you can find other disks, right-click and select "Compress Volume" 4. Enter the space you want to expand to compress, and then click "OK" to obtain the available space. 2. The disks are not adjacent 1. To expand a disk, you can

How to use PHP's Phar extension? How to use PHP's Phar extension? May 31, 2023 pm 11:31 PM

With the development of PHP and the continuous expansion of application scenarios, Phar extension has become an important part of PHP programming. Phar is the abbreviation of PHPArchive, which can package multiple PHP files and resources into a single file for easy distribution and management. This article will introduce how to use PHP's Phar extension for packaging and management. Installing the Phar extension First, we need to check whether PHP has the Phar extension installed. Under Linux, enter the following command through the terminal: php -m

See all articles