I have a lot of classes in multiples subfolders that I load using this autoloader :
spl_autoload_register(function ($class) {
$class = str_replace('\\', DIRECTORY_SEPARATOR, strtolower($class));
if(file_exists(FILES_PATH.'classes/'.$class.'.class.php')){
require_once(FILES_PATH.'classes/'.$class.'.class.php');
}
});
So if i do new Folder\subFolder\Myclass, it works.
The classes in folders are all in a namespace.
All these classes must use the database class, and the problem is here :
When the class is in a namespace and search the database class, it can't find it.
(DB class is in global namespace)
So I try to put "use BDD" (Bdd is the db class) and it still doesn't work, because Bdd is using PDO and so i must do "use bdd, pdo;" in EVERY classes of the project...
I find this stupid. Is this normal ?
Is there a better way to autoload, without using namespaces ?
It's pretty darn simple:
If you're in a namespace like so:
namespace Foo;
all names of all classes are resolved relative to that namespace. Any Bar will mean the class Foo\Bar, not the "global" Bar. If you want to refer in any way, shape or form to a class which is not in the same namespace, say Bar\Baz (class Baz from the namespace Bar), you have two choices:
use a fully qualified name for the class, e.g.:
\Bar\Baz
where the leading \ means the class name shall be resolved from the top namespace, not the current local one, or
if this is getting annoying to do every time, alias it using:
use Bar\Baz;
which is shorthand for
use Bar\Baz as Baz;
which means any time you use "Baz" in this namespace you mean the class Bar\Baz, not Foo\Bar\Baz.
Yes, this applies to each file individually. If you want to refer to PDO in some namespace in some file, you either have to write \PDO to make it resolve to the "global" PDO class or you write use PDO at the top of the file to make a convenience alias. That's how namespaces work.
This applies to all use cases of any class name:
new \PDO
\PDO::staticMethod()
\PDO::CONSTANT
You can explicitly say that BDD is in the global namespace by doing this in your code:
$foo = new \BDD();
Then you should not need to use it.
Moving answer from one of my comments ;)
Using use \Pdo; in BDD class fixed the world :)
Related
I used use the keyword "use" generally above the class definition. Like this:
<?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
use \Codeception\Specify;
class agpaypalTest extends \Codeception\Test\Unit
{
protected $tester;
...
But now I realised, that I have to put the line for the trait Specify into the class definition. Like this:
<?php
namespace suites\plugins\content\agpaypal;
use \Codeception\Util\Fixtures;
use \Codeception\Verify;
class agpaypalTest extends \Codeception\Test\Unit
{
use \Codeception\Specify;
protected $tester;
...
I think it is because the package \Codeception\Specify; is a trait. But I do not understand why I couldn't reuse this trait when I set the line
use \Codeception\Specify;
before the class definition?
I would be happy if someone could point me to a hint or an explanaiton that explains to me where I should use the keyword "use" the best.
In PHP, the keyword use is used in 3 cases:
As class name alias - simply declares short name for a class (must be declared outside of the class definition)
(manual: Using namespaces: Aliasing/Importing )
To add a trait to a class (must be declared inside (at the top) of the class definition)
(manual: Traits)
In anonymous function definition to pass variables inside the function
(manual: Anonymous functions)
You can not import class with use keyword. You have to use include/require statement. Even if you use some php auto loader, still autoloader will have to use either include or require internally.
The Purpose of use keyword:
Consider a case where you have two classes with same name; you'll find it strange, but when you are working with big MVC structure, this happens. So if you have two classes with same name, put them in different name spaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the use statement so that it can make a decision which one is going to be used on.
Here refer this
How does the keyword 'use' work
use is basically including a class in the file to use it.
There are two ways to include a class file in another file.
The most general is require or include method. Another method is using composer. Assume this Directory Structure
Project
|
|--- Folder A
| |
| |---UserRegistration.php
|
|---Example
|
|--TestUserRegistration.php
In Folder A there is UserRegistartion.php and you want to use the code in TestUserRegistration.php In UserRegistration.php It can be class, trait or Interface
Method 1.
In TestUserRegisteration.php you can include or require file UserRegistartion.php
and use it
Method 2
Using Composer. In UserRegistration.php you define namespace FolderA; as the first line of code. Then write your code as you do. So Now you want to use this file in TestUserRegistration.php you do
include vendor/autoload.php;
use FolderA\UserRegistration;
Which one is better and why?
Method 2 using composer is the best method. In method 1 wherever you want to include UserRegistration you have to find the relative path to UserRegistration file. So lets assume some day you need to change the directory structure your application will break as the relative path you had provided now it does'nt exist.
But in Method 2 you always use the namespace you provided \ The filename instead of where you want to use. So even you change the directory structure you don't have to got all codes and modify the path. It will work as it was.
To know more study about how to use namespace and composer.
I'm trying to rewrite an OO PHP site (that loosely follows an MVC structure) so it uses namespaces - and want to follow PSR-0.
In the current site I have a class (called APP) which is full of static methods that I call all over the place to handle things such as getting config data eg; APP::get_config('key').
Obviously with namespacing, I would need to call \TheNameSpace\App::get_config('key'). I use this class frequently, so want to avoid having to prefix the namespace every time I use it. I do call methods in it from within other classes, which would usually be under a sub-namespace - so changing the namespace at the top of the file won't really work.
So, I guess my question is, what is the easiest way to have a 'global' class with methods that I can call anywhere without having to prefix with the namespace each time?
namespace Foo;
use Bar;
Then you do not have to do \Bar\fn
So in your case:
namspace Foo;
use TheNameSpace\App;
App::get_config('blah')
Read the section in the php manual on using/aliasing namespaces.
http://www.php.net/manual/en/language.namespaces.importing.php
You can exclude the namespace by using "use". You can name it whatever you want.
use TheNamespace\App as App //You can name it anything here
App:config('key');
At top of your scripts add
use TheNameSpace\App as MyApp
for example. You can then use it like
app = new MyApp();
in your scripts. Of course you needn't to use an alias here. Just
use TheNameSpace\App
app = new App();
will work, too.
A global class that's implementing this one is bad style and you shouldn't do it like this:
class MyApp extends TheNameSpace\App { }
....
myApp = new MyApp();
I have a file with a class Resp. The path is:
C:\xampp\htdocs\One\Classes\Resp.php
And I have an index.php file in this directory:
C:\xampp\htdocs\Two\Http\index.php
In this index.php file I want to instantiate a class Resp.
$a = new Resp();
I know I can use require or include keywords to include the file with a class:
require("One\Classes\Resp.php"); // I've set the include_path correctly already ";C:\xampp\htdocs". It works.
$a = new Resp();
But I want to import classes without using require or include. I'm trying to understand how use keyword works. I tried theses steps but nothing works:
use One\Classes\Resp;
use xampp\htdocs\One\Classes\Resp;
use htdocs\One\Classes\Resp;
use One\Classes;
use htdocs\One\Classes; /* nothing works */
$a = new Resp();
It says:
Fatal error: Class 'One\Classes\Resp' not found in C:\xampp\htdocs\Two\Http\index.php
How does the keyword use work? Can I use it to import classes?
No, you can not import a class with the use keyword. You have to use include/require statement. Even if you use a PHP auto loader, still autoloader will have to use either include or require internally.
The Purpose of use keyword:
Consider a case where you have two classes with the same name; you'll find it strange, but when you are working with a big MVC structure, it happens. So if you have two classes with the same name, put them in different namespaces. Now consider when your auto loader is loading both classes (does by require), and you are about to use object of class. In this case, the compiler will get confused which class object to load among two. To help the compiler make a decision, you can use the use statement so that it can make a decision which one is going to be used on.
Nowadays major frameworks do use include or require via composer and psr
1) composer
2) PSR-4 autoloader
Going through them may help you further.
You can also use an alias to address an exact class. Suppose you've got two classes with the same name, say Mailer with two different namespaces:
namespace SMTP;
class Mailer{}
and
namespace Mailgun;
class Mailer{}
And if you want to use both Mailer classes at the same time then you can use an alias.
use SMTP\Mailer as SMTPMailer;
use Mailgun\Mailer as MailgunMailer;
Later in your code if you want to access those class objects then you can do the following:
$smtp_mailer = new SMTPMailer;
$mailgun_mailer = new MailgunMailer;
It will reference the original class.
Some may get confused that then of there are not Similar class names then there is no use of use keyword. Well, you can use __autoload($class) function which will be called automatically when use statement gets executed with the class to be used as an argument and this can help you to load the class at run-time on the fly as and when needed.
Refer this answer to know more about class autoloader.
use doesn't include anything. It just imports the specified namespace (or class) to the current scope
If you want the classes to be autoloaded - read about autoloading
Don’t overthink what a Namespace is.
Namespace is basically just a Class prefix (like directory in Operating System) to ensure the Class path uniqueness.
Also just to make things clear, the use statement is not doing anything only aliasing your Namespaces so you can use shortcuts or include Classes with the same name but different Namespace in the same file.
E.g:
// You can do this at the top of your Class
use Symfony\Component\Debug\Debug;
if ($_SERVER['APP_DEBUG']) {
// So you can utilize the Debug class it in an elegant way
Debug::enable();
// Instead of this ugly one
// \Symfony\Component\Debug\Debug::enable();
}
If you want to know how PHP Namespaces and autoloading (the old way as well as the new way with Composer) works, you can read the blog post I just wrote on this topic: https://enterprise-level-php.com/2017/12/25/the-magic-behind-autoloading-php-files-using-composer.html
You'll have to include/require the class anyway, otherwise PHP won't know about the namespace.
You don't necessary have to do it in the same file though. You can do it in a bootstrap file for example. (or use an autoloader, but that's not the topic actually)
The issue is most likely you will need to use an auto loader that will take the name of the class (break by '\' in this case) and map it to a directory structure.
You can check out this article on the autoloading functionality of PHP. There are many implementations of this type of functionality in frameworks already.
I've actually implemented one before. Here's a link.
I agree with Green, Symfony needs namespace, so why not use them ?
This is how an example controller class starts:
namespace Acme\DemoBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class WelcomeController extends Controller { ... }
Can I use it to import classes?
You can't do it like that besides the examples above. You can also use the keyword use inside classes to import traits, like this:
trait Stuff {
private $baz = 'baz';
public function bar() {
return $this->baz;
}
}
class Cls {
use Stuff; // import traits like this
}
$foo = new Cls;
echo $foo->bar(); // spits out 'baz'
The use keyword is for aliasing in PHP and it does not import the classes. This really helps
1) When you have classes with same name in different namespaces
2) Avoid using really long class name over and over again.
Using the keyword "use" is for shortening namespace literals. You can use both with aliasing and without it. Without aliasing you must use last part of full namespace.
<?php
use foo\bar\lastPart;
$obj=new lastPart\AnyClass(); //If there's not the line above, a fatal error will be encountered.
?>
Namespace is use to define the path to a specific file containing a class e.g.
namespace album/className;
class className{
//enter class properties and methods here
}
You can then include this specific class into another php file by using the keyword "use" like this:
use album/className;
class album extends classname {
//enter class properties and methods
}
NOTE: Do not use the path to the file containing the class to be implements, extends of use to instantiate an object but only use the namespace.
I can't get dynamic instantiating of classes in PHP to work when my files are namespaced.
PHP seems to be completely ignorant of the use keywords on top of my files, as I try to instantiate classes dynamically based upon the value of a variable.
Is there a good solution to this, besides hardcoding the namespace when dynamically instantiating classes?
Here's some quick samples to show what I mean:
Code new two('one'); results in that the class one isn't found with the below two files being included:
File1:
namespace uno;
use dos;
class one {
function __construct($what) {
new $what;
}
}
File2:
namespace dos;
class two { }
File 3:
new one('two'); // Doesn't work!
Either full-qualified
new \uno\one('two');
or defined by use
use uno\one;
new one('two');
or (relative) qualified (but that makes not much sense with a one-level namespace)
use uno;
new uno\one('two');
With deeper namespace it makes more sense
use path\to\myNamespace;
new myNamespace\foo\BarClass;
or put it in the same namespace
namespace uno;
new one('two');
See http://php.net/language.namespaces.rules
use MyNamespace;
class NonPersistentStorage implements StorageInterface
Both are in MyNamespace. Yet PHP looks for MyNamespace\NonPersistentStorage and StorageInterface (instead of MyNamespace\StorageInterface). Am I missing something?
PHP Namespaces work a bit different than in other languages. When you import a namespace, you aren't really bringing classes into scope, you're just aliasing the namespace. Importing only one level of namespace does absolutely nothing. Even when you import something, you still need to reference its bottommost namespace.
For example, if you have this:
foo.php:
namespace Bar\Baz\Biz;
class Foo
{}
Here is how you use it:
blah.php:
use Bar\Baz\Biz;
$var=new Biz\Foo();
See how I still have to reference it using Biz, even though I imported it?
However, you can get around this using aliases:
blah.php:
use Bar\Baz\Biz\Foo as Foo;
$var=new Foo();
As you can see, I no longer have to qualify it.
Unfortunately, however, there is no "import all" in PHP; if you want to do what's done above, you have to alias each and every class you want to import.
Actually, that "use" declaration does absolutely nothing. You should import (use) namespaces when they are deeper in the namespace hierarchy (e.g. use Foo\Bar\Baz) or when you want to give them an alias (e.g. use Foo as Bar). I think you wanted to declare that the file itself belongs to MyNamespace:
namespace MyNamespace;
class NonPersistentStorage implements StorageInterface { /* ... */ }
Or, you may also want to import separate functions and classes, using the same syntax as for namespaces.
Try using:
use MyNamespace;
class NonPersistentStorage implements MyNamespace\StorageInterface