Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP 5.3 autoloader

I would like to use the PSR-0 Standard way to autoload classes without requiring to add includes, e.g. how can I replace the code below with the autoloading mechanism:

namespace Example;
use MyLib\Controller;
include_once './library/MyLib/Controller/AbstractController.php';
class MyController extends Controller\AbstractController {
[...]

So in the example above, it shows that in every controllers I need to include the abstract controller, which is crazy...

I have found the PSR-0 code here:

https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md

https://gist.github.com/221634

But I have no idea how I need to implement this in my application.

like image 418
Matthew Avatar asked Mar 05 '26 21:03

Matthew


1 Answers

You need include (include/require statement) the file with the autoloader code in the first script of your application

If you choose for use the Composer's autoloader as @Skpd said then you should have a code like this in the top of your first PHP script.

include_once __DIR__ . '/composer_autoloader.php'

$loader = new \Composer\Autoload\ClassLoader();
$loader->add('MyLib', __DIR__.'/library/');
$loader->register();

If you decide to use Composer as your vendor manager then add your custom namespaces to your composer.json and include vendor/autoload.php

like image 174
Maks3w Avatar answered Mar 08 '26 13:03

Maks3w



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!