【问题标题】:PHP Namespace Class Naming ConventionPHP 命名空间类命名约定
【发布时间】:2016-03-25 09:50:49
【问题描述】:

我目前关注 PSR-2 和 PSR-4。在尝试命名几个类时,我遇到了一个小难题。这是一个例子。

我有一个基本的 REST 客户端,\Vendor\RestClient\AbstractClient。我有这个抽象客户端的两个实现:

  • \Vendor\GoogleClient\GoogleClient
  • \Vendor\GithubClient\GithubClient

由于命名空间已经指定了域,客户端类的命名是否多余?我应该改为命名我的课程吗:

  • \Vendor\GoogleClient\Client
  • \Vendor\GithubClient\Client

这意味着客户端代码将始终使用以下内容:

use Vendor\GoogleClient\Client;

$client = new Client();

这比:

use Vendor\GoogleClient\GoogleClient;

$client = new GoogleClient();

但第一个选项允许我们通过仅更改 use 语句轻松地换出实现。

PSR4 指定InterfacesAbstractClasses 应分别以Interface 为后缀和以Abstract 为前缀,但它没有说明特定于域的前缀/后缀。有什么意见/建议?

【问题讨论】:

  • 如果 PSR 没有说明这一点,那大概是由个人风格决定的。

标签: php naming-conventions naming psr-4 psr-2


【解决方案1】:

这完全取决于您,因为 PSR 中对此没有命名约定。但是你必须记住你的决定是如果你决定

  • \Vendor\GoogleClient\Client
  • \Vendor\GithubClient\Client

并且你喜欢同时使用它们(use

use Vendor\GoogleClient\Client;
use Vendor\GithubClient\Client;

$client = new Client();

您会遇到错误,因为Client 不是唯一的。

当然你仍然可以像这样一次性使用它们

use Vendor\GoogleClient\Client as GoogleClient;
use Vendor\GithubClient\Client as GithubClient;

$client1 = new GoogleClient();
$client2 = new GithubClient();

或没有use 喜欢

$client1 = new Vendor\GoogleClient\Client();
$client2 = new Vendor\GithubClient\Client();

但是,如果你计划程序员可以通过从

use Vendor\GoogleClient\Client;
$client = new Client();

use Vendor\GithubClient\Client;
$client = new Client();

这比将所有new GoogleClient() 语句也更改为new GithubClient() 要容易得多。

结论
你会发现这个决定很大程度上取决于你自己的需要和喜好。自行决定哪一个更适合您。

【讨论】:

  • 我个人更喜欢较短的形式。它更干净,并迫使开发人员更加关注。
【解决方案2】:

请注意,还可以考虑使用以下代码进行重构:

  • \Vendor\Client\Google
  • \Vendor\Client\GitHub

逻辑是:从不太具体到最具体。

话虽如此,这通常是不可能的。

【讨论】:

    猜你喜欢
    • 2018-03-21
    • 2023-03-03
    • 1970-01-01
    • 2015-03-30
    • 1970-01-01
    • 1970-01-01
    • 2016-12-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多