lievikoff
83
2
Tips

Namespaces in PHP and Classes with same names

Posted 10 months ago by lievikoff

Hi. Could you please help me understand best practice of naming classes in PHP using namespaces?

Example: I have two classes called the same - Assets but they have different namespaces: Acme\App and Acme\App\Admin.

Code:

  • app/assets.php (supposed to enqueue frontend assets):
namespace Acme\App;

Assets {
    public function __construct() {
        $this->some_functionality();
    }
}
  • app/admin/assets.php (supposed to enqueue backend assets):
namespace Acme\App\Admin;

Assets {
    public function __construct() {
        if ( ! is_admin() ) {
            return;
        }

        $this->some_functionality();
    }
}

Question: The idea of namespaces is get rid of prefixes and group code. But is that not confusing? Should i name the Acme\App\Admin\Assets class with a prefix Admin like Admin_Assets?

PS: Of course i could keep all assets in the same class with a condition where to enqueue them, but it is probably much better idea to split in two files.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.