How can I use composer's autoload to automatically load the function libraries and class libraries compiled by myself ?, Composerautoload
1. Run the command composer init to generate the composer. json file, and edit the autoload option as follows:
There are two main options: files and psr-4.
Files is the function library that requires composer to automatically help us load (excluding classes), as long as the file path of the function library is written in the following array.
Psr-4, as the name suggests, is a class library based on psr-4 (http://www.php-fig.org/psr/psr-4/) Rules to automatically load mappings, As long as in the object after"Namespace": "path"
Write your own class library information.
After modification, just executecomposer update
.
Note: After composer. json is updated, it takes effect only after composer update is executed.
{ "name": "libo21/spider_script", "description": "general spider for sina finance market group", "type": "project", "require": { "php": ">=5.3.10" }, "autoload": { "files":[],"psr-4":{ "Core\\" :"core/"} }}
Let's dig deeper and explore the principle of autoload.
After composer. json is modified and update is executed,./vender/composer/autoload_psr4.php is modified. For example, a corresponding relationship is added to a project of mine:
<?php// autoload_psr4.php @generated by Composer$vendorDir = dirname(dirname(__FILE__));$baseDir = dirname($vendorDir);return array( 'Core\\' => array($baseDir . '/core'),);
2. Automatic Loading Test
For example, we create a folder core in the same directory of composer. json and write the ClassTest class:
1 <?php2 namespace Core;3 class ClassTest{4 public function getName(){5 return "test";6 }7 }8 ?>
Compile test. php and run test. php. The "test" content is displayed on the page:
<? Phprequire_once './vendor/autoload. php'; $ obj = new Core \ ClassTest (); // instantiate class echo $ obj-> getName ();?>
Complete!