Using Composer’s Autoload

Every package should be responsible for autoloading itself, what are you trying to achieve with autoloading classes that are out of the package you define? One workaround if it’s for your application itself is to add a namespace to the loader instance, something like this: <?php $loader = require ‘vendor/autoload.php’; $loader->add(‘AppName’, __DIR__.’/../src/’);

Autoload classes from different folders

I see you are using controller_***** and model_***** as a class naming convention. I read a fantastic article, which suggests an alternative naming convention using php’s namespace. I love this solution because it doesn’t matter where I put my classes. The __autoload will find it no matter where it is in my file structure. It … Read more

Autoloading classes in PHPUnit using Composer and autoload.php

Well, at first. You need to tell the autoloader where to find the php file for a class. That’s done by following the PSR-0 standard. The best way is to use namespaces. The autoloader searches for a Acme/Tests/ReturningTest.php file when you requested a Acme\Tests\ReturningTest class. There are some great namespace tutorials out there, just search … Read more

How to create a PSR-4 autoloader for my project?

If you are using composer, you do not create the autoloader but let composer do its job and create it for you. The only thing you need to do is create the appropriate configuration on composer.json and execute composer dump-autoload. E.g.: { “autoload”: { “psr-4”: {“App\\”: “src/”} } } By doing the above, if you … Read more

How to use spl_autoload() instead of __autoload()

You need to register autoload functions with spl_autoload_register. You need to provide a “callable”. The nicest way of doing this, from 5.3 onwards, is with an anonymous function: spl_autoload_register(function($class) { include ‘classes/’ . $class . ‘.class.php’; }); The principal advantage of this against __autoload is of course that you can call spl_autoload_register multiple times, whereas … Read more

How do I use PHP namespaces with autoload?

Class1 is not in the global scope. Note that this is an old answer and things have changed since the days where you couldn’t assume the support for spl_autoload_register() which was introduced in PHP 5.1 (now many years ago!). These days, you would likely be using Composer. Under the hood, this would be something along … Read more

tech