thinkphp Framework design and extended detailed _php examples

Source: Internet
Author: User
Tags documentation exception handling php framework

Thinkphp Framework is a very popular and widely used PHP framework in China, we take a deep look at some simple development examples to explore the development convenience of this framework, as well as the ease of expansion of the design. At the same time from the source analysis point of view of the framework of some deficiencies, as far as possible to do a comprehensive and objective evaluation. This assumes that you have used the thinkphp framework, the basic use of the method please refer to the official documentation.

I. Framework layering and URL routing

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

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

Here we strongly recommend that you:
1, the business separate stratification, do not have to 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');
}

Benefits are good reusability, if the future to develop WAP page, wrote a different controller, you can reuse service, if the future data storage changes, such as the database from MySQL migrated to MongoDB and so on, then modify model can be, The service still doesn't need any changes.

2, the basic module and business module separate, do not refer to each other. The underlying module (for example, user profile) only provides data interfaces without controller and view.
The three-tier catalog can already deal with general web applications, more complex Web applications we can define different entry files to load different application to solve. More complex applications? Portals and Super scale sites, it's not a PHP framework that solves all the problems, requires its own middleware and custom framework.

thinkphp support 4 kinds of URL access mode , respectively:

1, Normal mode , traditional URL mode, all parameters are separated, such as
Http://localhost/tp/index.php?m=ucai&c=user&a=index¶=xxx
Route parameter: M parameter represents module, C represents Controller, a represents access method
2. Compatibility mode
http://localhost/tp/index.php?s=/Ucai/User/index/para/xxx
The routing parameter is assembled by the s parameter, of course the data parameter can not be put in s parameter.
3,pathinfo mode
Http://localhost/tp/index.php/Ucai/User/index/para/xxx
This pattern puts the entry file together with the real script, meaning clear and easy to SEO
4,rewrite mode
Http://localhost/tp/Ucai/User/index/para/xxx
This mode hides the entry file through the rewrite configuration of the Web server, and is more friendly
Where the pathinfo and rewrite modes require Web server support. Thinkphp has a configuration that needs to be set to which mode, which is actually used when creating a URL link in the U method, as long as the Web server support is available in any way.
It is also recommended that thinkphp do not need to configure, but to remember the way users access, as long as the first access to which mode, the subsequent generation of URLs are generated in this way, because the user has access to there is no support for the 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 just need to add the following routing configuration to the module configuration file, which can be simpler if you 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 that meets a variety of requirements. Of course, we recommend that you do not misuse the routing configuration, the appropriate small number of configuration can bring better SEO effect, but a large number of configuration will give the maintenance and modification of the project to bring difficulties.

Second, thinkphp expansion

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

Iii. Database-driven extensions

Although thinkphp provides a large number of database drivers, it does not meet all of the requirements. For example, our data is probably not implemented directly by accessing the database, but by forwarding it through some middleware (such as a C program) for better performance, which requires extended database-driven support.
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 extensions even if completed, and then configure Db_type= ' Custom ' in the configuration file, you can use. The request here represents the query, execute represents the change data, all other operations are parsed in model, packaged as SQL statements to invoke the two methods to execute.
For example, the simplest query method I have implemented is to invoke SQLite to execute the SQL statement through the shell command:

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 to support sqlite3, through the PDO way to connect to. The actual application environment may be to access the middle-tier ports by connecting the 4-tier protocol to obtain 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 extension.
If we were to join the login verification feature, we would design our own parent class controller as usual, and then all the other controller would inherit from here. But with behavior will become simpler and more flexible, we only need to add a behavior on tags.php (no words in the Config 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 the execution according to the state.

namespace Ucai\behavior;
Class Authbehavior {
The execution portal for the behavior extension must be run
Public function run (& $return) {
The action that does not need to be validated is set 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, 5 seconds to jump ... ');
}
}
}
}

For pages that do not need to be logged in, we can add a configuration to the controller, and all not configured will require logon verification.

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

Here you can make a comparison between inheritance and behavior implementation of login verification, which may feel very different. But in a complex project, this function will be very much, 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 appear to be able to.
In the above configuration we also found a configuration outputbehavior more to explain the problem, we have not guessed that this behavior I was used in view to output some common variables, such as JSCSS domain name and path. Do you need a public method before behavior, and then each page will call once, or rewrite the view's class code? There is a lot of convenience with 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');
     }
}

Extension Summary: Through behavior extensions and database-driven extensions you can see that thinkphp provides a flexible extension and enhancement mechanism to meet a wide range of requirements. Other storage, caching, logging, template engines, and so on, can be easily extended if needed.

Five, source analysis and deficiencies

First, let's analyze the general process of framework execution:
index.php (entry, debug mode, application path)
--> thinkphp.php (define path and access mode)
--> Think\think (class loader, exception handling, read shared configuration)
--> think\app (Request URL Dispatch parsing, execution dispatch parsing result)
--> EXEC executes the user-defined controller action method
--> Think\dispatcher (to parse M, C, a, and parameters according to URL pattern, load module configuration)
--> Think\controller (call view, wrapper, and redirect)
As you can see, the internal process of the framework is actually relatively simple, with 2 important classes:
Think\hook: Monitor the various stages of the app, Action, view, and execute the behavior
Think\behavior: Configurable (configuration file) can be added or deleted (code)

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

1, the macro definition too much, difficult to maintain and modify
Recommendation: Only a few macros are defined in individual files, and the rest are packaged with class constants
2, process-oriented code too much, encapsulation is not clear
Suggestion: Wrapping with object-oriented thinking
For example: URL parsing and wrapping, now generates app macros in dispatcher, then reads macros 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 responsible for parsing and generating the URLs, so the code structure is much clearer.
3, some functions and class code encapsulation too much, reuse and improve inconvenient
Recommendation: Use a combination to encapsulate independent feature content
For example: Model of the checksum function, can be completely independent of the class, can also be used for non-model object calls. And now the calibration interface is the model of the protective method, only in the model of the CREATE function call, the outside must be the Create method to verify.
4, code specifications and style issues
You want the code style to be more normative and standard, such as the DB class as the parent of the template method, and you should define all the methods that model requires by using an abstract method or throwing an exception form. In fact, some method subclasses are not needed, and the DB class is not implemented.

Vi. Summary

thinkphp as a popular PHP framework in China, it does bring convenience to our development. The framework developer has a thorough understanding of the web process and has a good grasp of PHP's functional applications. The framework defines flexible configurations and extensions to accommodate a variety of requirements, providing a rich set of components and modules to speed development. Finally, Thinkphp's documentation and community support are perfect, which is an essential part of the framework's popularity. We also hope that thinkphp will be able to better their own structure, playing 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.