Replies: 2 comments
-
<?php
class Varien_Autoload
{
protected static ?Varien_Autoload $_instance = null;
public static function instance(): Varien_Autoload
{
if (!self::$_instance) {
self::$_instance = new Varien_Autoload();
}
return self::$_instance;
}
public static function register(): void
{
spl_autoload_register([self::instance(), 'autoload']);
}
public function autoload(string $class): bool
{
foreach ($this->getPaths($class) as $path) {
if (@include $path) {
return true;
}
}
return false;
}
private function getPaths(string $class): array
{
return [
$this->getPsr0Path($class),
$this->getPsr4Path($class),
];
}
private function classPartsToUpperCase(string $class, string $separator): string
{
return str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace($separator, ' ', $class)));
}
private function getPsr0Path(string $class)
{
return $this->classPartsToUpperCase($class, '_') . '.php';
}
private function getPsr4Path(string $class)
{
return $this->classPartsToUpperCase($class, '\\') . '.php';
}
} EDIT: I forgot that file_exists() won't use include_path. Considering it's an anti-pattern anyway, it makes sense. So, I just made it try to include the file. I quickly tested this and it works. |
Beta Was this translation helpful? Give feedback.
0 replies
-
This will not work with the service locator methods. That's a different story and one that requires a lot more work and testing. This is just to allow you to do simple things like |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
Summary (*)
Add support for PSR-4 autoloading in addition to the current PSR-0 support.
Examples (*)
\OpenMage\SomeModule\Model\SomeClass
=>app/code/OpenMage/SomeModule/Model/SomeClass.php
I want to be able to do
$someClass = new SomeClass
and it load the correct file (assuming this is in the\OpenMage\SomeModule\Model\
namespace or I have a use statement at the top of the file)Proposed solution
Add another autoloader. https://www.php-fig.org/psr/psr-4/examples/
Beta Was this translation helpful? Give feedback.
All reactions