composer of autoload you have written to automatically load the library and the library?

1, using the composer init command generates composer.json files, and edit the autoload options as follows:

Which also contains two main options: files and psr-4.

files that need composer automatically help our library loaded (without class), as long as the file path in the array function library to write back.
psr-4 name implies, is based psr-4 ( http://www.php-fig.org/psr/psr-4/ ) autoloader library regular correspondence relationship, as long as the subject subsequent to  "命名空间": "路径" the way information can write your own library.
After editing, just run it composer updateto complete the corresponding work.

Note: After each finished updating composer.json, must be performed after the composer update to take effect.

 

Copy the code
{
    "name": "sui/test",
    "description": "test",
    "type": "project",
    "require": {
        "php": ">=5.3.10"
    },
    "autoload": {
    	"files":[],
	"psr-4":{
	   "Test\\" :"core/"
	}
    }
}
Copy the code

Let's dig deep, explore autoload principle.
After we modify composer.json and execution update, we will modify ./vender/composer/autoload_psr4.php, such as one of my projects, which adds such a correspondence relationship:

1
2
3
4
5
6
7
8
9
10
<?php
 
// autoload_psr4.php @generated by Composer
 
$vendorDir  = dirname(dirname( __FILE__ ));
$baseDir  = dirname( $vendorDir );
 
return  array (
     'Test\\'  =>  array ( $baseDir  '/core' ),
);

2, automatic load test

For example, we built on the same directory folder composer.json core, and write ClassTest categories:

Copy the code
1 <?php
2 namespace Test;
3 class ClassTest{
4     public function getName(){
5         return "test";
6     }
7 }
8 ?>
Copy the code

Write test.php, and run test.php, you can see the print on the screen "test" Content:

1
2
3
4
5
<?php
require_once  __DIR__. '/vendor/autoload.php' ;
$obj  new  \Test\ClassTest(); //实例化类
echo  $obj ->getName();
?>

  

Guess you like

Origin www.cnblogs.com/boundless-sky/p/11407958.html