Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to understand the Design and extension of ThinkPHP Framework

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article focuses on "how to understand the design and extension of ThinkPHP framework". Interested friends may wish to take a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn "how to understand ThinkPHP framework design and extension".

1. Frame layering and url routing

The installation of the framework is very simple, you can download it and put it in the directory of the web server, but it is recommended that you do not use the default entry file location, but put it in a separate directory to protect code and data. For example, my entry file and web server configuration directory are located in the web directory (index.php in the outer framework is not deleted but not used):

Like most MVC frameworks, we only need to extend our Controller and View according to the framework's directory structure, and some pages are developed. ThinkPHP provides a three-tier structure of Module, Controller and Action to organize its own url (version 3.1 is called grouping, Action and method,3.2 is more international). The directory structure is as follows:

Here is a strong suggestion:

1. Businesses are layered separately and do not need to be placed in Controller and Model. For example, I force the definition of the business layer name to Service through the extension function library Application/Common/Common/function.php:

Function service ($name)

{

Return D ($name, 'Service')

}

The advantage is that reusability is good, if you want to develop wap pages in the future and write different Controller, you can reuse service. If the future data storage changes, such as migrating the database from mysql to mongodb, you can modify Model, and service still does not need any modification.

2. The basic module and the business module are separated and do not refer to each other. The basic module (such as basic user information) provides only the data interface, not Controller and View.

The three-tier directory can already deal with general web applications. For more complex web applications, we can define different entry files and load different Application to solve the problem. More complex applications? Portals and very large-scale websites, that is not a php framework can solve all the problems, need their own middleware and customized framework.

ThinkPHP supports four url access modes, which are:

1. Normal mode, traditional url mode, all parameters are separated, for example

Http://localhost/tp/index.php?m=Ucai&c=User&a=index¶=xxx

Routing parameters: M parameter for module, c for controller, a for access method

2. Compatibility mode

Http://localhost/tp/index.php?s=/Ucai/User/index/para/xxx

Routing parameters are assembled by s parameters. Of course, data parameters do not have to be placed in s parameters.

3. Pathinfo mode

Http://localhost/tp/index.php/Ucai/User/index/para/xxx

This mode puts the entry file and the real script together, which is clear in meaning and convenient for SEO.

4. Rewrite mode

Http://localhost/tp/Ucai/User/index/para/xxx

This mode is more friendly by hiding the entry file through the rewrite configuration of the web server.

Pathinfo and rewrite modes need to be supported by web servers. ThinkPHP has a configuration that needs to be set to which mode, which is actually used when generating url links in the U method, as long as the web server supports it.

It is also recommended that ThinkPHP do not need to be configured, but remember the method of user access. As long as which mode is used for the first access, the generated url will be generated in this way, because there is no question of whether to support it if the user has already accessed it.

If the normal url does not meet our requirements, we can further optimize the url by configuring routing. For example, we want to make the url configuration easier.

Http://localhost/tp/Ucai/login/xxx

We only need to add the following routing configuration to the module configuration file, which can be more simplified if we use regular expressions

'URL_ROUTE_RULES' = > array (

'login/:para' = >' Ucai/User/index'

'login' = >' Ucai/User/index'

),

Here we can see that the ThinkPHP framework supports a rich hierarchy and url configuration to meet a variety of needs. Of course, we recommend that you do not abuse the routing configuration, an appropriate small amount of configuration can bring better seo results, but a large number of configurations will bring difficulties to the maintenance and modification of the project.

II. ThinkPHP extension

ThinkPHP itself contains a wealth of components and drivers, let's take database-driven extension and behavior extension as an example to understand the extension design of ThinkPHP.

III. Database-driven extension

Although ThinkPHP provides many database drivers, it does not meet all the requirements. For example, our data is probably not achieved through direct access to the database, but forwarded through some middleware (such as C programs) to achieve better performance, so we need to extend the database driver to support.

The extension is very simple, create your own driver in the DB/Driver directory, such as Custom.php, then implement the request and execute method extensions, and then configure DB_TYPE='custom', in the configuration file. Here, request represents a query, execute means to change the data, and all other operations are parsed in Model, wrapped as sql statements that call these two methods.

For example, in the simplest query method I have implemented, calling sqlite through the shell command executes the sql statement:

Public function query ($str) {

$cmd = sprintf ('sqlite3% s', $this- > config ['params'] [' dbfile'], $str)

Exec ($cmd, $arr)

}

Of course, this is just an example. ThinkPHP itself supports sqlite3, and you can connect through pdo. The actual application environment may be to access the middle layer port to obtain data by connecting layer 4 protocol.

IV. Behavior behavior extension

Behavior behavior design is the core of ThinkPHP framework, which provides maximum support for system scalability and customization through behavior configuration and extension.

If we want to add login authentication, as a rule, we will design our own parent class, Controller, and then all other Controller inherits from this. However, with Behavior, it will become more simple and flexible. We just need to add a Behavior to tags.php (if not, create a new one in the configuration directory):

Return array (

'action_begin' = > array (' Ucai\ Behavior\ AuthBehavior')

'view_begin' = > array (' Ucai\ Behavior\ OutputBehavior')

);

The program calls this Behavior when it executes to the action_begin process, and we can jump or terminate execution based on the state.

Namespace Ucai\ Behavior

Class AuthBehavior {

/ / the execution entry of the behavior extension must be run

Public function run (& $return) {

/ / set the action that does not require verification to true

If (! $return ['AUTH_PUBLIC']) {

If (service ('User')-> checkLogin ())

{

$return = true

}

Else

{

Header ('Content-Type: text/html; charset=utf-8')

Redirect (U ('User/index', array (' url' = > $_ SERVER ['HTTP_REFERER'])), 5,' login required, jump after 5 seconds.')

}

}

}

}

For pages that do not require login, we can add configuration in Controller, and login verification is required for all pages that are not configured.

Public $config = array ('AUTH_PUBLIC' = > true)

Here you do a comparison between inheritance and Behavior login authentication, it may feel that there is little difference. But in a complex project, there will be a lot of this functionality, if each function is placed in the parent class, it will be very large, and some subclasses may not be needed, it will be easy to customize the process with Behavior.

In the above configuration, we also found a configuration OutputBehavior that is more illustrative. Have you guessed that this Behavior is used to output some common variables in view, such as the domain name and path of jscss. Before Behavior, did you need a public method and then call it once on every page, or rewrite the class code of View? It is much more convenient to have Behavior.

Namespace Ucai\ Behavior

Class OutputBehavior {

Public function run (& $return) {

$view =\ Think\ Think::instance ('Think\ View')

$view- > assign ('STATIC_URL',' http://p3.ucai.cn/static');

}

}

Summary of extensions: through Behavior extensions and database-driven extensions, you can see that ThinkPHP provides flexible extension and enhancement mechanisms to meet many needs. Other storage, caching, logging, template engines, etc., can also be easily expanded if necessary.

V. Source code analysis and deficiency

First, let's analyze the general process of framework execution:

Index.php (portal, debug mode, application path)

-- > ThinkPHP.php (define path and access mode)

-- > Think\ Think (classloader, exception handling, read common configuration)

-- > Think\ App (request url scheduling resolution and execute scheduling resolution result)

-- > exec executes the Action method of the user-defined Controller

-- > Think\ Dispatcher (parse M, C, An and parameters according to url mode, load module configuration)

-- > Think\ Controller (call view, wrapper, and redirect)

As you can see, the internal process of the framework is actually relatively simple, and there are two very important classes:

Think\ Hook: monitor the stages of App, Action, View, and execute Behavior

Think\ Behavior: configurable (configuration file) can be added or deleted (code)

In the process of analyzing the source code, we also saw some shortcomings:

1. It is difficult to maintain and modify macros because of too many definitions.

Suggestion: only a few macros are defined in individual files, and the rest are wrapped in class constants

2. Too much process-oriented code and unclear encapsulation

Suggestion: package with object-oriented thought

For example, the parsing and wrapper of url now generates the APP macro in Dispatcher, then reads the macro in the U method and generates the final url. In fact, you can define a class to wrap such as UrlHelper, and the two methods of the class, parse and generate, are respectively responsible for parsing and generating url, so the code structure will be much clearer.

3. Some functions and class codes are encapsulated too much, so it is not convenient to reuse and improve them.

Suggestion: use combinations to encapsulate independent functional content

For example: the check function of Model can be classified into independent classes, and it can also be used for non-Model object calls. The current verification interface is a protective method of Model, which can only be called in the create function of Model, and can only be verified by the create method.

4. Code specification and style issues

I want the code style to be more standardized and standard. For example, the DB class, as the parent class of template methods, should define all the methods needed for Model with abstract methods or in the form of throwing exceptions. In fact, some method subclasses are not needed, but the Db class is not implemented.

At this point, I believe you have a deeper understanding of "how to understand ThinkPHP framework design and extension". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report