ThinkPHP framework design and extension details, thinkphp framework details _ PHP Tutorial

Source: Internet
Author: User
ThinkPHP framework design and extension details, and thinkphp framework details. ThinkPHP framework design and expansion details, thinkphp framework details ThinkPHP framework is a widely used php framework in China, we will learn more about ThinkPHP framework design and expansion from some simple Development examples.

ThinkPHP framework is a widely used php framework in China. let's take a look at some simple Development examples to learn more about the ease of development and the scalable design that this framework brings to us. At the same time, we also look at some shortcomings of the framework from the perspective of source code analysis, and try to make a comprehensive and objective evaluation. Assume that you have used the ThinkPHP framework. for basic usage instructions, see the official documentation.

I. framework hierarchy and url routing

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

Like most MVC frameworks, we only need to expand our Controller and View according to the directory structure of the framework, and some pages will be developed. ThinkPHP provides a Module, Controller, and Action layer-3 structure to organize its own URLs (version 3.1 is called grouping, Action, and method, and version 3.2 is more international). the directory structure is as follows:

We strongly recommend that you:
1. separate business layers without putting them in the Controller and Model. for example, I use the extended function library Application/Common/function. php to forcibly define the Service layer name as Service:

function service($name)
{
return D($name, 'Service');
}

The advantage is good reusability. if you want to develop wap pages and write different controllers in the future, you can reuse the service. if data storage changes in the future, for example, if you migrate a database from mysql to mongodb, you can modify the Model and the service still does not need to be modified.

2. the basic modules and business modules are separated and do not reference each other. Basic modules (such as basic user information) only provide data interfaces without Controller and View.
The layer-3 directory can be used for general web applications. for more complex web applications, we can define different entry files to load different applications. More complex applications? Portal and ultra-large-scale websites, it is not a php framework that can solve all the problems. you need your own middleware and custom framework.

ThinkPHP supports four url access modes, Respectively:

1,Normal modeIn the traditional url mode, all parameters are separated, for example
Http: // localhost/tp/index. php? M = Ucai & c = User & a = index detail = xxx
Route parameter: m parameter indicates the module, c indicates the controller, and a indicates the access method.
2,Compatibility mode
Http: // localhost/tp/index. php? S =/Ucai/User/index/para/xxx
Route parameters are assembled by s parameters. of course, data parameters do not need to be placed in s parameters.
3,Pathinfo mode
Http: // localhost/tp/index. php/Ucai/User/index/para/xxx
In this mode, the entry file and the real script are put together, with a clear meaning and convenient SEO
4,Rewrite mode
Http: // localhost/tp/Ucai/User/index/para/xxx
In this mode, you can use the rewrite configuration of the web server to hide the entry file, which is more friendly.
The pathinfo and rewrite modes must be supported by the web server. ThinkPHP has a configuration that needs to be set to which mode, which is actually used to generate url links in the U method. when accessing ThinkPHP, you only need to use which method the web server supports.
We also recommend that ThinkPHP do not need to be configured, but remember the user access mode. as long as the first access mode is used, the url generated in the future will be generated in this mode, because the user has already accessed it, there is no support issue.

If the normal url cannot meet our requirements, we can further optimize the url by configuring the route. for example, we want to make url configuration easier.
Http: // localhost/tp/Ucai/login/xxx
You only need to add the following routing configuration in the module configuration file. if you use a regular expression, it can be simpler.

'URL_ROUTE_RULES'   =>  array(
'login/:para' => 'Ucai/User/index',
'login' => 'Ucai/User/index',
),

Here we can see that the ThinkPHP framework supports a wide range of layers and url configurations, meeting various requirements. Of course, we recommend that you do not misuse route configurations. a small number of configurations can bring better seo results, but a large number of configurations will make it difficult to maintain and modify the project.

II. ThinkPHP extension

ThinkPHP is rich in components and drivers. let's take database-driven extension and behavior extension as an example to learn about ThinkPHP's extension design.

III. database-driven scaling

ThinkPHP provides many database drivers, but it cannot meet all requirements. For example, our data may not be implemented through direct access to the database, but through some Middleware (such as C program) for forwarding to achieve better performance, in this case, you need to extend the database driver to support.
Expansion is very simple. you can create your own Driver in the DB/Driver Directory, for example, Custom. php, and then implement the extension of the request and execute methods, and then configure DB_TYPE = 'custom' in the configuration file. Here, the request indicates a query, and the execute indicates changing the data. All other operations will be parsed in the Model and packaged into an SQL statement to call these two methods for execution.
For example, the simplest query method I implemented is to use shell commands to call sqlite to execute SQL statements:

public function query($str) {
$cmd = sprintf('sqlite3 %s "%s"', $this->config['params']['dbfile'], $str);
exec($cmd, $arr);
}

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

4. Behavior scaling

Behavior design is the core of the ThinkPHP framework. through Behavior configuration and expansion, it provides maximum support for system scalability and customization.
If we want to add the login verification function, we will design our own parent class Controller as usual, and then all other controllers will inherit from it. However, with Behavior, it becomes simpler and more flexible. we only need to add a Behavior in 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'),
);

This Behavior will be called when the program executes the action_begin process. we can jump to or terminate the execution according to the status.

Namespace Ucai \ Behavior;
Class AuthBehavior {
// The execution entry for behavior extension must be run.
Public function run (& $ return ){
// Set the action that does not need to be verified 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 in 5 seconds... ');
}
}
}
}

For pages that do not require logon, you can add configurations to the Controller. logon verification is required for all pages that do not require logon.

public $config = array('AUTH_PUBLIC' => true);

Here, we will compare inheritance with Behavior login verification, which may be slightly different. However, in a complex project, there will be a lot of such functions. if each function is placed in the parent class, it will be very huge, and some sub-classes may not need it, at this time, you can use Behavior to customize the process.
In the above configuration, we also found a configuration OutputBehavior that can better illustrate the problem. Have you guessed that this Behavior is used to output some common variables in the view, such as the domain name and path of jscss. Before Behavior is available, do you need a public method and call each page once, or rewrite the class code of the View? With Behavior, it is much more convenient.

namespace Ucai\Behavior;
class OutputBehavior {
public function run(&$return) {
$view = \Think\Think::instance('Think\View');
$view->assign('STATIC_URL', 'http://p3.ucai.cn/static');
}
}

Conclusion: with Behavior extension and database-driven extension, we can see that ThinkPHP provides flexible extension and enhancement mechanisms to meet many requirements. Other storage, caching, logs, and template engines can be easily expanded as needed.

V. source code analysis and deficiency

First, let's analyze the general process of framework execution:
Index. php (entry, debugging mode, application path)
--> ThinkPHP. php (define the path and access mode)
--> Think \ Think (class loader, exception handling, read common configuration)
--> Think \ App (request url scheduling parsing and execution of scheduling parsing results)
--> Exec: execute the user-defined Controller Action method
--> Think \ Dispatcher (parse M, C, A, and parameters based on url mode, and load module configuration)
--> Think \ Controller (call view, packaging, and redirection)
As you can see, the internal process of the framework is actually relatively simple, and there are two very important classes:
Think \ Hook: listen to various stages of the App, Action, and 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 see some shortcomings:

1. too many macro definitions, difficult to maintain and modify
Suggestion: only a few macros are defined in some files, and the rest are packaged using class constants.
2. too many process-oriented code and unclear encapsulation
Suggestion: use object-oriented ideas for packaging
For example, the APP macro is generated in the Dispatcher, and then the macro is read in the U method and the final url is generated. In fact, you can define a class to wrap such as UrlHelper. The two methods of the class, parse and generate, are responsible for parsing and generating URLs respectively, so that the code structure is much clearer.
3. some functions and class code are too encapsulated, making reuse and improvement inconvenient.
Suggestion: use combinations to encapsulate independent functional content
For example, the Model validation function can be fully isolated into classes, or used for non-Model object calls. The current verification interface is a protective method of the Model. it can only be called in the create function of the Model, and can only be verified through the create method.
4. code specifications and style issues
We hope that the code style can be more standardized and standard. for example, the DB class as the parent class of the template method should define all the methods required by the Model by using abstract methods or throwing exceptions. In fact, some method subclasses are not required, but Db classes are not implemented.

VI. Summary

ThinkPHP, as a popular php framework in China, has indeed brought convenience to our development. Framework developers have a thorough understanding of web processes and are proficient in php function applications. The framework defines flexible configuration and expansion to meet various needs, and provides a wide range of components and modules to accelerate development. Finally, ThinkPHP's documentation and community support are well-developed, which is also an indispensable part of the framework popularity. We also hope ThinkPHP will improve its own structure and create the best php framework in the future.

The broad ThinkPHP framework is a widely used php framework in China. let's take a look at some simple Development examples...

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.