简体   繁体   中英

Am I using namespaces, autoload, and aliasing correctly?

I've been reading a lot of posts on StackOverflow but I'm not really sure I'm using namespaces, autoloading, and aliasing correctly. This is functioning fine, but I'm not sure I'm properly using these concepts. I've listed some reasons why I think this setup is incorrect at the bottom of the post.

Imagine the following directory structure:

\public_html
  - index.php
  \Classes
   \A
    - One.php
   \B
    - Two.php

One.php is structured like:

<?php
namespace Classes\A;
class A { ....

Two.php is structured like:

<?php
namespace Classes\B;
class B { ....

Then, in index.php I do something like:

<?php
use Classes\A\One as One;
use Classes\B\Two as Two;

spl_autoload_register(function ($className) {
...
});

... ?>    

So, a couple things that bug me about this:

  1. If I am doing aliasing (the "use" statements) I still need to list out all of the files. Aren't we trying to avoid doing this by using autoload?

  2. If I want to use internal classes, I need to add a line such as "use \\mysqli;" into the class that uses this and do things like "new \\mysqli()". Seems kind of messy?

  3. If a class extends a class from another namespace (say Two.php extends One.php for example) then I need to include "use \\Classes\\A\\One as One;" in One.php which seems to be what we want to avoid in the first place

  1. You don't have to reference all of your namespaced classes via a use statement. You can use partial namespaces.

     use Classes\\A; new A\\One(); 

    So you can see if you had another class in the A namespace it could be instantiated with

     new A\\Three(); 
  2. There are many things in the global namespace, you don't need to define them with use . You can just call them \\mysqli() . Yes it's a bit unsightly but it allows you to make a function called mysqli in your own code without worrying about collisions with globally namespaced functions.

  3. I'm not sure I follow you on this one. You don't need to do a use in the base class which references itself.

Ultimately it kinda seems like you view use almost like include when they are very different, use , in this context, is a convenience thing so you don't have to type out full namespaces every time.

Your Autoloader also doesn't need to know about your namespaces. The autoloader just tells PHP how to load a class. So if it sees a class come in with the name Classes\\A\\One you can make it look in the directory /Classes/A for a file called One.php and include it. PHP will make sure that the class is allocated in the proper namespace. The autoloader is just a convenience thing to keep you from having to do includes and requires in each of your PHP files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM