I have had a slight problem with autoloading in my namespace. As shown on the PHP manual here: http://us.php.net/manual/en/language.namespaces.rules.php you should be able to autoload namespace functions with a full qualified name e.g. \glue\common\is_email().
Thing is I have a function spl_autoload_register(array($import, "load")); within the initial namespace but whenever I try and call \glue\common\is_email() from the initial namespace it will not pass that autoload function but when using new is_email() (in the context of a class) it will. I don't get it the manual says I can autoload from fully qualified names but I can't :.
Here's my code:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
$import = new import();
spl_autoload_register(array($import, "load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = \glue\common\is_email($email);
I also tried this code as well:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
use glue\common;
$import = new import();
spl_autoload_register(array($import, "load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = common\is_email($email);
and finally this code:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
use glue\common\is_email as F;
$import = new import();
spl_autoload_register(array($import, "load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = F($email);
Here's the only right answer.
Every namespace needs its own spl_autoload_register() function.
also, spl_autoload_register() syntax changed in 5.3:
spl_autoload_register(__NAMESPACE__ . "\\className::functionName"));
The following should work:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
$import = new import();
spl_autoload_register(__NAMESPACE__ . "\\$import::load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = \glue\common\is_email($email);
Here is some live code that Just works!
in ../WebPageConsolidator.inc.php:
class WebPageConsolidator
{
public function __construct() { echo "PHP 5.2 constructor.\n"; }
}
in test.php:
<?php
namespace WebPage;
class MyAutoloader
{
public static function load($className)
{
require '../' . __NAMESPACE__ . $className . '.inc.php';
}
}
spl_autoload_register(__NAMESPACE__ . "\\MyAutoloader::load");
class Consolidator extends \WebpageConsolidator
{
public function __construct()
{
echo "PHP 5.3 constructor.\n";
parent::__construct();
}
}
// Output:
// PHP 5.3 constructor.
// PHP 5.2 constructor.
So I know it works.
The misconception in the question of the OP is probably that functions/methods would be subject to autoloading – which they are not. Autoloading is only triggered by referencing classes.
This being said there still remains the question about autoloading classes in namespaces:
As of 2017 the current PHP-FIG standard for autoloading is PSR-4 which provides the following autoloader code for namespaced classes:
<?php
/**
* An example of a project-specific implementation.
*
* After registering this autoload function with SPL, the following line
* would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
* from /path/to/project/src/Baz/Qux.php:
*
* new \Foo\Bar\Baz\Qux;
*
* #param string $class The fully-qualified class name.
* #return void
*/
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'Foo\\Bar\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});
The full spec text can be found at PSR-4: Autoloader.
The code example above (and another one to autoload from multiple namespaces) can be found at Example Implementations of PSR-4 (or GitHub: fig-standards/accepted/PSR-4-autoloader-examples.md).
Use Composer to autoload your PHP Classes.
Check out how to do it in my recent blog post: https://enchanterio.github.io/enterprise-level-php/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
Related
I have had a slight problem with autoloading in my namespace. As shown on the PHP manual here: http://us.php.net/manual/en/language.namespaces.rules.php you should be able to autoload namespace functions with a full qualified name e.g. \glue\common\is_email().
Thing is I have a function spl_autoload_register(array($import, "load")); within the initial namespace but whenever I try and call \glue\common\is_email() from the initial namespace it will not pass that autoload function but when using new is_email() (in the context of a class) it will. I don't get it the manual says I can autoload from fully qualified names but I can't :.
Here's my code:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
$import = new import();
spl_autoload_register(array($import, "load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = \glue\common\is_email($email);
I also tried this code as well:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
use glue\common;
$import = new import();
spl_autoload_register(array($import, "load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = common\is_email($email);
and finally this code:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
use glue\common\is_email as F;
$import = new import();
spl_autoload_register(array($import, "load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = F($email);
Here's the only right answer.
Every namespace needs its own spl_autoload_register() function.
also, spl_autoload_register() syntax changed in 5.3:
spl_autoload_register(__NAMESPACE__ . "\\className::functionName"));
The following should work:
namespace glue;
require_once 'import.php';
use glue\import as import;
use glue\core\router as router;
$import = new import();
spl_autoload_register(__NAMESPACE__ . "\\$import::load"));
/** Works and echos glue\router **/
$router = new router();
/** Don't do nothing **/
$cheese = \glue\common\is_email($email);
Here is some live code that Just works!
in ../WebPageConsolidator.inc.php:
class WebPageConsolidator
{
public function __construct() { echo "PHP 5.2 constructor.\n"; }
}
in test.php:
<?php
namespace WebPage;
class MyAutoloader
{
public static function load($className)
{
require '../' . __NAMESPACE__ . $className . '.inc.php';
}
}
spl_autoload_register(__NAMESPACE__ . "\\MyAutoloader::load");
class Consolidator extends \WebpageConsolidator
{
public function __construct()
{
echo "PHP 5.3 constructor.\n";
parent::__construct();
}
}
// Output:
// PHP 5.3 constructor.
// PHP 5.2 constructor.
So I know it works.
The misconception in the question of the OP is probably that functions/methods would be subject to autoloading – which they are not. Autoloading is only triggered by referencing classes.
This being said there still remains the question about autoloading classes in namespaces:
As of 2017 the current PHP-FIG standard for autoloading is PSR-4 which provides the following autoloader code for namespaced classes:
<?php
/**
* An example of a project-specific implementation.
*
* After registering this autoload function with SPL, the following line
* would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
* from /path/to/project/src/Baz/Qux.php:
*
* new \Foo\Bar\Baz\Qux;
*
* #param string $class The fully-qualified class name.
* #return void
*/
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'Foo\\Bar\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});
The full spec text can be found at PSR-4: Autoloader.
The code example above (and another one to autoload from multiple namespaces) can be found at Example Implementations of PSR-4 (or GitHub: fig-standards/accepted/PSR-4-autoloader-examples.md).
Use Composer to autoload your PHP Classes.
Check out how to do it in my recent blog post: https://enchanterio.github.io/enterprise-level-php/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
It is possible to make accessible a Class within spl_autoload_register (automatically)?
For example, I using spl_autoload_register in index.php:
<?php
class Utils {
public function example() {
echo 'Hello word!';
}
}
spl_autoload_register(function($class)
{
$relative_class = strtolower(str_replace('\\', '/', $class));
$file = './src/' . $relative_class . '.php';
if (is_file($file)) {
require_once $file;
}
});
$user = new \Controllers\Foo\User;
This new \Controllers\Foo\User; autoload this file ./src/controllers/foo/user.php
user.php:
<?php
namespace Controllers/Foo;
class User
{
public function foo() {
//Something...
}
}
If I need to use a Utils class I'll have to add new \Controllers\Foo\User in the file user.php like this:
public function foo() {
\Utils::example();
}
or
<?php
namespace Controllers/Foo;
use \Utils as Utils;
class User
{
public function foo() {
Utils::example();
}
}
It is possible to make accessible to Utils class within spl_autoload_register (automatically)? I would use without use \Utils as Utils; and without backslash (\Utils::).
You can't. That's the whole point of using namespaces. You can reference a class whitout backslash or use statement only if it is in the same namespace you are using it. You can't hack the autoloader to automagically import the target class into the current namespace changing its namespace on the fly.
If your class doesn't belong to a named namespace, then it is in the global namespace and you still have to use with \ or use. The same for import or use keywords in python, java, go, .net, c/c++, etc.
There is no standard anything to do this besides using use ... as ... or "backslash" (\), however we can "cheat the PHP" using eval() within the spl_autoload_register() to extend the Utils class within the namespace.
Only use this if really necessary, prefer to use "backslash" (\) or use \Utils as Utils
Example (read comments in code):
<?php
class Utils {
public static function example() {
echo 'Hello World!';
}
}
spl_autoload_register(function($class)
{
$relative_class = strtolower(str_replace('\\', '/', $class));
$file = './src/' . $relative_class . '.php';
if (is_file($file)) {
$np = explode('\\', $class); //Dividi string
//Check if class exists in namespace (prevent conflicts)
if (class_exists(implode('::', $np)) === false) {
//Remove "class name", use only "namespace"
array_pop($np);
//evaluate a namespace in eval (extends the Utils class)
eval(
'namespace ' . implode('\\', $np) . ' {' . PHP_EOL .
'class Utils extends \Utils {}' . PHP_EOL .
'}'
);
}
require_once $file;
}
});
$user = new \Controllers\Foo\User;
$user->foo(); //Show "Hello word!"
I admit that it is an ugly hack and maybe I will not use, but it's still a hint yes.
Note: use \Utils as Utils not work in eval
I have an index.php that require Test1 class trough spl_autoload_register(). In the Test1 class the Test2 class is required with the same autoload but this error occurred:
Fatal error: DOMDocument::registerNodeClass(): Class Test2 does not
exist in...
I tried to see if the autoload work writing $test2 = new Test2(); and it works well. So with other tests I realized that with registerNodeClass() the autoload doesn't include the Test2 class file.
Is there anyone who can help me?
Test1.php
<?php
namespace Test;
use Test\Test2;
class Test1
{
function __construct($html)
{
$this->dom = new \DOMDocument();
#$this->dom->loadHTML($html);
$this->dom->registerNodeClass('DOMElement', 'Test2');
}
}
?>
Test2.php
<?php
namespace Test;
class Test2 extends \DOMElement
{
//bla, bla, bla...
}
?>
index.php
<?php
require_once('./autoload.php');
use Test\Test1;
$html = 'something';
$test = new Test1($html);
?>
autoload.php (it is the same used by Facebook for the php-sdk)
<?php
/**
* An example of a project-specific implementation.
*
* After registering this autoload function with SPL, the following line
* would cause the function to attempt to load the \Foo\Bar\Baz\Qux class
* from /path/to/project/src/Baz/Qux.php:
*
* new \Foo\Bar\Baz\Qux;
*
* #param string $class The fully-qualified class name.
* #return void
*/
spl_autoload_register(function ($class) {
// project-specific namespace prefix
$prefix = 'Test\\';
// base directory for the namespace prefix
$base_dir = __DIR__ . '/src/';
// does the class use the namespace prefix?
$len = strlen($prefix);
if (strncmp($prefix, $class, $len) !== 0) {
// no, move to the next registered autoloader
return;
}
// get the relative class name
$relative_class = substr($class, $len);
// replace the namespace prefix with the base directory, replace namespace
// separators with directory separators in the relative class name, append
// with .php
$file = $base_dir . str_replace('\\', '/', $relative_class) . '.php';
// if the file exists, require it
if (file_exists($file)) {
require $file;
}
});
?>
class Test2 is within namespace Test, so in order to do new Test2() you must be within the namespace Test or you can specify the fully qualified name (ie new Test\Test2()) to instantiate the class.
When you call $this->dom->registerNodeClass('DOMElement', 'Test2');, DOMDocument does something to the affect of:
$extendedClass = 'Test2';
$obj = new $extendedClass();
And it doesn't find Test2 because that code isn't called from the Test namespace.
So you would need to pass the fully qualified class name (w/ namespace).
Use: $this->dom->registerNodeClass('DOMElement', 'Test\Test2');
If someone work with GO! framework, can you help me.
I install framework on php 5.3.13. Demo example is working.
But my own example doesn't work. Aspect(method beforeMethodExecution) is not perfomed.
Here is my code.
Main file:
//1 Include kernel and all classes
if (file_exists(__DIR__ .'/../../vendor/autoload.php')) {
$loader = include __DIR__ .'/../../vendor/autoload.php';
}
// 2 Make own ascpect kernel
use Go\Core\AspectKernel;
use Go\Core\AspectContainer;
class Kernel extends AspectKernel{
/**
* Configure an AspectContainer with advisors, aspects and pointcuts
*
* #param AspectContainer $container
*
* #return void
*/
public function configureAop(AspectContainer $container)
{
}
}
//3 Initiate aspect kernel
$Kernel = Kernel::getInstance();
$Kernel->init();
//4 Include aspect
include(__DIR__.'/aspectclass/AspectClass.php');
$aspect = new DebugAspect();
//5 register aspect
$Kernel->getContainer()->registerAspect($aspect);
//6 Include test class
include(__DIR__.'/class/class1.php');
//7 Execute test class
$Class = new General('test');
$Class->publicHello();
File with test class:
class General{
protected $message = '';
public function __construct($message)
{
$this->message = $message;
}
public function publicHello()
{
echo 'Hello, you have a public message: ', $this->message, "<br>", PHP_EOL;
}
}
File with aspect:
use Go\Aop\Aspect;
use Go\Aop\Intercept\FieldAccess;
use Go\Aop\Intercept\FunctionInvocation;
use Go\Aop\Intercept\MethodInvocation;
use Go\Lang\Annotation\After;
use Go\Lang\Annotation\Before;
use Go\Lang\Annotation\Around;
use Go\Lang\Annotation\Pointcut;
use Go\Lang\Annotation\DeclareParents;
use Go\Lang\Annotation\DeclareError;
class DebugAspect implements Aspect{
/**
* Method that should be called before real method
*
* #param MethodInvocation $invocation Invocation
* #Before("execution(General->*(*))")
*
*/
public function beforeMethodExecution(MethodInvocation $invocation)
{
$obj = $invocation->getThis();
echo 'Calling Before Interceptor for method: ',
is_object($obj) ? get_class($obj) : $obj,
$invocation->getMethod()->isStatic() ? '::' : '->',
$invocation->getMethod()->getName(),
'()',
' with arguments: ',
json_encode($invocation->getArguments()),
PHP_EOL;
}
}
As you know, go-aop isn't a PHP extension, so it couldn't transform classes that were loaded directly via require or include. Internally it tries to overwrite the source code on-the-fly, but it should receive a control (via integration with composer or custom autoloader class).
So, you have an error here:
//6 Include test class
include(__DIR__.'/class/class1.php');
You explicitly load this class into memory and there is no way to transform it from userland. To pass a control to the framework, you should make this explicitly. Look at the line AopComposerLoader.php#L99 to have an idea how it works. Here we include a source file via the stream source filter that pass control to the framework and it can transform the class to weave an aspects.
To fix your example just change an include to the following:
include (FilterInjectorTransformer::rewrite(__DIR__.'/class/class1.php'));
recently I was learning zend framework 2, and there's a problem annoying me for a long time, things look like this:
<?php
namespace Album\Model;
// Add these import statements
use Zend\InputFilter\InputFilter;
use Zend\InputFilter\InputFilterAwareInterface;
use Zend\InputFilter\InputFilterInterface;
class Album implements InputFilterAwareInterface
{
public $id;
public $artist;
public $title;
protected $inputFilter;
public function exchangeArray($data)
{
$this->id = (isset($data['id'])) ? $data['id'] : null;
$this->artist = (isset($data['artist'])) ? $data['artist'] : null;
$this->title = (isset($data['title'])) ? $data['title'] : null;
}
// Add content to these methods:
public function setInputFilter(InputFilterInterface $inputFilter)
{
throw new \Exception("Not used");
}
//....
?>
This code was a section of the "skeleton application" programme, which was a tutorial of ZF2. The first time I see the programme, I don't understand what's the usage of "namespace" and "use", because this two keyword doesn't exist in php5.2(also the same in the earlier edition), so I go to see the manual and try to understand it.I write a programme to simulate what really happens:
<?php
use script\lib\test;
$o = new test();
echo $o->getWelcome();
function __autoload( $className ) {
$classname = strtolower( $classname );
require_once( dirname( __FILE__ ) . '/' . $classname . '.php' );
}
?>
the programme above works well, of course I created two folders named script and lib, and there's a file named test.php.
Seems like every thing is clear, zend framework also has a autoload function, BUT when I noticed the codes in "skeleton application programme", there was a namespace in the beginning, so I adds the namespace to my programme too:
<?php
namespace test;
use script\lib\test;
$o = new test();
echo $o->getWelcome();
function __autoload( $className ) {
$classname = strtolower( $classname );
require_once( dirname( __FILE__ ) . '/' . $classname . '.php' );
}
?>
the page returned me inforamtion as following:
Fatal error: Class 'script\lib\test' not found in E:\wamp\www\test\test_29.php on line 6
I tried to change the namespace's name such as script\lib, script\lib\test...
but it's useless.
Any answer will be appreciated, thanks.
Now I will give you more details about this issue:
To understand the usage of "namespace" and "use", I looked over the materials on php.net:
http://php.net/manual/en/language.namespaces.importing.php
In this page, there was a section of code looks like this:
Example #1 importing/aliasing with the use operator
<?php
namespace foo;
use My\Full\Classname as Another;
// this is the same as use My\Full\NSname as NSname
use My\Full\NSname;
// importing a global class
use ArrayObject;
$obj = new namespace\Another; // instantiates object of class foo\Another
$obj = new Another; // instantiates object of class My\Full\Classname
NSname\subns\func(); // calls function My\Full\NSname\subns\func
$a = new ArrayObject(array(1)); // instantiates object of class ArrayObject
// without the "use ArrayObject" we would instantiate an object of class
?>
Now let's review the programme I write in the above:
<?php
namespace test;
use script\lib\test;
$o = new test();
echo $o->getWelcome();
function __autoload( $className ) {
$classname = strtolower( $classname );
require_once( dirname( __FILE__ ) . '/' . $classname . '.php' );
}
?>
It's the same, I'm trying to simulate that instance, if we don't use the autoload function:
<?php
namespace test;
use script\lib\test;
require_once 'script/lib/test.php';
$o = new test();
echo $o->getWelcome();
?>
It works well too, BUT when I use __autoload function to load the class file, there's something wrong.
I don't konw where's problem, OR any body tried to write an instance to put the "Example #1" into practice? I will wait for your answer.
I think you're misunderstanding what's going on here.
Namespaces allow you to, more or less, create "directories" for your classes. So you can create the \Foo class and the \Test\Foo class (where \ represents the "root" of your application).
The way autoloading works is that your files mirror your namespacing. So foo.php would be in the root of your autoloading but you would create /test/foo.php for \Test\Foo
The use keyword has two uses. One is to alias class files and the other is, in PHP 5.4 or later, to bring in a Trait into your current class.
Now, to your question. First, Let's look at your code
<?php
namespace test;
use script\lib\test;
$o = new test();
echo $o->getWelcome();
This is confusing. You declare a namespace (which you don't need to do here) but then you alias it to script\lib\test. PHP is now looking for a file called /script/lib/test.php, which your error message says doesn't exist. But you said the file does exist so let's look at that
public function getWelcome() {
return 'welcome';
}
This isn't a class. It's a function. For this example you need a complete class
<?php
namespace script\lib;
class test {
public function getWelcome() {
return 'welcome';
}
}
Lastly, let's talk autoloading. You don't need to use use with autoloading. Your autoloader should take care of that for you. You should, however, use spl_autoload_register(), as __autoload() is soon to be depreciated.
From ZF2 docu
Zend\Loader\StandardAutoloader is designed as a PSR-0-compliant autoloader. It assumes a 1:1 mapping of the namespace+classname to the filesystem, wherein namespace separators and underscores are translated to directory separators.
Read more about: PSR-0
So if you're using namespaces the classname that gets send to the autoloader doesn't look like test. It looks like YOUR_NAMESPACE\test. YOUR_NAMESPACE is the namespace that you defined in the class with namespace YOUR_NAMESPACE;
PSR-0 is a standard that says: Your namespace should reflect your filesystem. You only have to replace the backslashes with forward slashes. Or _ with / if you're using pseudo namespaces like in ZF1. (Album_Model_Album)
So output the $className that is sent to your autoloader and you will see..