Is it possible to make a Class accessible in all namespaces?

Asked

Viewed 244 times

2

The question is similar to this Instantiate class outside namespace and has a good answer /a/68198/3635

However I would like to do this automatically. For example:

It is possible to make a Class be accessible in all namespaces? No use \ or use \Classe as Class;.

For example, I’m using spl_autoload_register in the index php.:

<?php
class Utils {
   public function example() {
      echo 'Olá mundo!';
   }
}

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; autocharges the file ./src/controllers/foo/user.php

user php.:

<?php
namespace Controllers/Foo;

class User
{
    public function foo() {
        //Something...
    }
}

If I need to use class Utils I’ll have to add in user php. something like:

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 the class Utils be accessible to all namespaces?
  • Or the moment I carry a class by spl_autoload_register the class Utils be automatically added to the current namespace?

I want to use the Utils class without adding use \Utils as Utils; or without needing backslash (\Utils::), it is possible?

Just the Utils class, I’d like to use it like this:

<?php
namespace Controllers/Foo;

class User
{
    public function foo() {
        Utils::example();
    }
}
  • I think namespaces can create enough confusion without a feature like that...

  • @Oeslei I was also confused rs, now I am with a little more understanding, I would like an opinion from you. Let me explain first, the use of namespaces goes beyond psr-4 for me, I want to be able to create classes with the same name following the MVC standard and for this without error when declaring a Modal class and a Controller class with the same name. The controllers only work inside the namespace Controller; and the models within namespace Model; another reason is that I can create controllers and models in subfolders and if by chance the name of a class repeats they will still be in namespaces ...

  • ... different, so when I load a controller like this new \Controller\user\account; he will not conflict with this new \Model\user\account; for example. I am reluctant to use "namespaces" because I see that rarely these conflicts can happen, since we usually only use one controller at a time. I really don’t know if this namespace business is the best way :( what do you think? @Oeslei

  • I really like namespaces: they prevent name conflicts, identify their function more easily (model, control, etc.) and are extremely useful for implementing an efficient autoloader. What you said about control classes only being loaded by other classes in the controller namespace (same with the model) is what you want to happen or is as you understand it?

  • Maybe I misexpressed, who loads everything is the autoloader, who calls the Model is the controller and the controller is called by the Routes. When I say load I mean declare, if I don’t use namespaces I would have to create a name for a model and another name for a controller. But it’s just an example, I won’t always use a specific model with the same name for a controller, I can use as many models as I want within an action, as far as I’ve gone. The idea of using namespaces is more for organization and the developer has more facility to understand which Controller belongs to such model @Oeslei

  • It’s more of an organizational concept, but I’m reluctant, I’m preferring to follow an interface similar to the laravel4, I’m still reluctant of everything :(

  • I believe this Soen topic will help you choose... http://stackoverflow.com/questions/28376462/laravel-5-namespaces

  • Thanks @Oeslei I’ll read :) - In the meantime http://answall.com/q/80060/3635

Show 3 more comments

1 answer

0


There is nothing standard to do this but use use or \, however we can "cheat" php using eval within the spl_autoload_register to extend the class within the namespace.

<?php
class Utils {
   public static function example() {
      echo 'Olá mundo!';
   }
}

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

        //Checa se a classe já existe no namespace especifico (previnir conflitos)
        if (class_exists(implode('::', $np)) === false) {

            //Remove o nome da classe, pois usaremos apenas o namespace
            array_pop($np);

            //executa um namespace dentro do eval "copiado" (estendendo a classe Utils)
            eval(
                'namespace ' . implode('\\', $np) . ' {' . PHP_EOL .
                'class Utils extends \Utils {}' . PHP_EOL .
                '}'
            );
        }

        require_once $file;
    }
});

$user = new \Controllers\Foo\User;
$user->foo(); //Irá exibir "Olá mundo!"

I admit it’s a scam and maybe I won’t use it, but it’s a hint yet yes.

Note: Use use \Utils as Utils does not work within eval

Browser other questions tagged

You are not signed in. Login or sign up in order to post.