This article introduces the PHP design pattern one of the namespace, the automatic loading class, PSR-0 encoding specification, now share to everyone, the need for friends can refer to
First, the namespace: solve the problem of the class name or function name conflict in the production environment when there are many cooperative development;
test1.php
<?phpnamespace test1;function Test () { echo ' Test1 the test () method under the namespace;}? >
test2.php
<?phpnamespace test2;function Test () { echo ' Test2 the test () method under the namespace;}? >
test.php
<?phprequire_once (' test1.php '); require_once (' test2.php '); Test1\test (); Call the test () method under the Test1 namespace Test2\test ();? >
Second, automatic loading class: To solve the problem of introducing too many dependent class files in the project;
demo1.php
<?phpclass demo1{ static function test () { echo ' Demo1 class, Test () method "; }}? >
demo2.php
<?phpclass demo2{ static function test () { echo ' Demo2 class, Test () method "; }}? >
demo.php
<?php//php5.3+ version, Spl_autoload_register () automatically registers the load class. The parameter is a custom function spl_autoload_register (' autoload ');//Customize an auto-load function, $class to the class name, without the need to pass parameters. Spl_autoload_register () method Auto-recognition function AutoLoad ($class) { require_once (__dir__. ') /'. $class. '. php ');} Demo1::test ();D emo2::test ();//php5.3 version, use the __autoload () method function __autoload ($class) { require_once (__dir__. ') /'. $class. '. php '); >
Third, PSR-0 coding specification
1), the namespace must be used and consistent with the absolute path of the file;
2), the first letter of the class name must be capitalized and consistent with the file name;
3), except the entry file, the PHP file must have only one class and no executable code;
Iv. writing a set of basic frameworks based on PSR-0 coding specifications
1), directory structure
the APP stores the code for business logic and functionality implementation |--controller |--home |--index.phpframe stores code unrelated to business logic, and the framework part |--autoloader.php Auto-load class index.php single entry file
autoloader.php
<?phpnamespace frame;class autoloader{ static function AutoLoad ($class) { require_once (BASEDIR. ') /'. Str_replace (' \ \ ', '/', $class). php ');} }? >
app/controller/home/index.php
<?phpnamespace app\controller\home;class index{ static function test () { echo ' Home Controller test () static method "; }}? >
index.php
<?phpdefine (' BASEDIR ', __dir__); require_once (BASEDIR. ') /frame/autoloader.php '); Spl_autoload_register (' frame\\autoloader::autoload '); App\controller\home\index::test ();//output: the test () static method under the Home controller?>