thinkphp Framework design and expansion of detailed _php

Source: Internet
Author: User
Keywords thinkphp frame design expansion
The thinkphp framework is a very well-known and widely used PHP framework in China, and we take a look at some of the simple development examples to learn more about the ease of development that this framework brings to us, as well as the scalable design. At the same time, from the perspective of source analysis of the framework of some shortcomings, as far as possible to do a comprehensive and objective evaluation. This assumes that you have already used the thinkphp framework, please refer to the official documentation for basic usage methods.

I. Framework layering and URL routing

The installation of the framework is very simple, after downloading into the Web server directory can be, but we recommend that you do not use the default portal file location, but into a separate directory, easy to protect code and data. For example, my portal file and Web server configuration directory are in the Web directory (the index.php in the outer frame is not deleted but not used):

As with most MVC frameworks, we just need to expand our controller and view by the framework's directory structure, and some pages will be developed. Thinkphp provides module, Controller, action three-layer structure to organize its own URLs (3.1 version called Grouping, action and method,3.2 more international), the directory structure is as follows:

It is strongly recommended that you:
1, the business is separate layer, do not put in controller and model, for example I here through the Extension function library application/common/common/function.php to enforce the definition of business layer name for service:

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

The advantage is good reusability, if in the future to develop WAP page, write a different controller, you can reuse service, if later data storage changed, such as the database from MySQL to MongoDB and so on, then modify model can, The service still does not require any modifications.

2, the basic module and business modules separate, do not reference each other. The base module (for example, user base information) only provides data interfaces without controller and view.
The three-tier catalog is already ready for general Web applications, and more complex Web applications we can define different portal files to load different application to solve. More complex applications? Portals and hyper-scale sites, it's not a PHP framework that solves all of the problems, requires its own middleware and custom frameworks.

thinkphp supports 4 types of URL access modes , namely:

1, Normal mode , traditional URL mode, all parameters are separated, for example
Http://localhost/tp/index.php?m=ucai&c=user&a=index¶=xxx
Route parameters: M parameter denotes module, C represents controller, a means access method
2. Compatibility mode
Http://localhost/tp/index.php?s=/Ucai/User/index/para/xxx
The routing parameters are assembled by the s parameter, and of course the data parameters may not be placed in the s parameter.
3.pathinfo mode
Http://localhost/tp/index.php/Ucai/User/index/para/xxx
This mode puts the entry file and the real script together, meaning clearly, also facilitates the SEO
4.Rewrite mode
Http://localhost/tp/Ucai/User/index/para/xxx
This mode is more friendly by hiding the portal file through the rewrite configuration of the Web server.
where pathinfo and rewrite modes require Web server support. Thinkphp has a configuration to be set to which mode, in fact, is used in the U method to generate a URL link in the time of use, when accessed as long as the Web server support in which way can be.
It is also recommended that thinkphp does not need to be configured, but rather to remember the way the user accesses, as long as the first access using which mode, the subsequent generation of the URL is generated in this way, because the user has access to there is no support problem.

If the normal URL does not meet our requirements, you can also configure the route to further optimize the URL, for example, we want to configure the URL more simple
Http://localhost/tp/Ucai/login/xxx
We only need to add the following routing configuration in the module configuration file, if you use regular expressions, you can simplify

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

Here we can see that the thinkphp framework supports a very rich hierarchy and URL configuration to meet a variety of needs. Of course, we recommend that you do not misuse the routing configuration, the appropriate amount of configuration can bring better SEO results, but a large number of configurations will be difficult to maintain and modify the project.

Second, thinkphp expansion

The thinkphp itself is rich in components and drivers, and we take a look at the extended design of thinkphp with examples of database-driven extensions and behavior extensions.

Third, database-driven expansion

Although thinkphp provides a multitude of database drivers, it does not meet all the requirements. For example, our data is probably not implemented by direct access to the database, but rather through some middleware (such as a C program) for better performance, you need to extend the database driver to support it.
The extension is very simple, create your own driver in the Db/driver directory, such as custom.php, and then implement the request and execute method extension even if completed, and then configure the file configuration db_type= ' Custom ', it can be used. Here the request represents the query, execute represents the change data, and all other operations are parsed in the model, wrapped in SQL statements called by the two methods to execute.
For example, the simplest query method I've implemented is to invoke SQLite from the shell command to execute the SQL statement:

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 support the sqlite3, through the PDO way to connect can. The actual application environment might be to access the middle-tier port by connecting the Layer 4 protocol to get the data.

Iv. Expansion of behavior behavior

Behavior behavior design is the core of the thinkphp framework, which provides maximum support for the scalability and customization of the system through behavioral configuration and expansion.
If we were to join the login verification feature, we would design our own parent controller as usual, and then all the other controllers would inherit from here. But with the behavior will become much simpler and more flexible, we just need to add a behavior on tags.php (no words in the Config directory new):

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 {
// 行为扩展的执行入口必须是run
public function run(&$return) {
//不需要验证的action设置为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, '需要登录,5秒后跳转。。。');
}
}
}
}

For pages that do not need to be logged in, we can add configurations to the controller, and all configurations that are not configured will require login verification.

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

Here everyone on the inheritance and behavior implementation of login verification to make a comparison, may feel that the difference is not small. But in a complex project, this can be a lot of functionality, if each function is placed in the parent class, it will be very large, and some subclasses may not need, this time with behavior to customize the process will be able to look good.
In the above configuration we also found a configuration outputbehavior more to explain the problem, we have not guessed that this behavior I am used in the view to output some common variables, such as JSCSS domain name and path. Before the behavior, do you need a public method, and then every page to call once, or rewrite the view class code? With the behavior, it seems to be 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');
}
}

Extension Summary: Behavior extensions and database-driven extensions as you can see, thinkphp provides a flexible extension and enhancement mechanism to meet a wide range of requirements. Other storage, caching, logging, template engine, etc. can be easily extended if needed.

V. Source code Analysis and deficiencies

Let's start by analyzing the approximate flow of framework execution:
index.php (entrance, debug mode, application path)
--thinkphp.php (define path and access mode)
--Think\think (ClassLoader, exception handling, read common configuration)
--think\app (request URL scheduling parsing, execution schedule parsing results)
--EXEC executes the user-defined Controller's action method
--Think\dispatcher (parse M, C, a and parameters according to URL mode, load module configuration)
--Think\controller (call view, wrapper, and redirect)
As you can see, the internal flow of the framework is actually relatively simple, and there are 2 important classes:
Think\hook: Monitor all stages of the app, Action, and view to perform behavior
Think\behavior: Configurable (config file) can be added and deleted (code)

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

1, macro definition too much, difficult to maintain and modify
Recommendation: Only a few macros are defined in individual files, the remainder is wrapped in class constants
2, too many process code, packaging is not clear
Recommendation: Packaging with object-oriented thinking
For example: URL parsing and wrapping, now is the creation of the app macro in dispatcher, then read the macro in the U method and generate 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 responsible for parsing and generating URLs, which makes the code much clearer.
3, some functions and class code encapsulation too much, reuse and improve inconvenient
Recommendation: Use a combination to encapsulate individual feature content
For example, the calibration function of model can be completely independent and can be used for non-model object invocation. Now the check interface is the model of the protective method, only in the model's create function call, outside must pass the Create method to verify.
4. Code specification and style issues
You want code styles to be more prescriptive and standard, such as the DB class as the parent of a template method, and you should define the method that all the model needs by using an abstract method or throwing an exception form. In fact, some method subclasses are not required, and the DB class is not implemented.

Vi. Summary

Thinkphp, as a popular PHP framework in China, has certainly brought convenience to our development. Framework developers have a thorough understanding of the web process, and the application of PHP's functions is very good. The framework defines flexible configurations and extensions to suit a variety of needs, providing a rich set of components and modules to accelerate development. Last but not least, thinkphp's documentation and community support are perfect, and this is an essential part of the framework's popularity. We also hope that thinkphp will be able to improve its own structure and make the best PHP framework.

  • 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.