0

随着现在越来越多的面向服务的 PHP 被开发出来,我发现自己有很多 PHP 文件,其中有这么长的代码块只是为了初始化。在 C++ 或 typescript 等其他语言中,您可以执行以下操作而无需所有重复。一个 PHP 示例:

namespace Test\Controllers;
use Test\Services\AppleService;
use Test\Services\BananaService;
use Test\Services\PearService;
use Test\Services\LemonService;
use Test\Services\PeachService;

class TestController{

    protected $appleService;
    protected $bananaService;
    protected $lemonService;
    protected $pearService;
    protected $peachService;

    public function __construct(
    AppleService $appleService,
    BananaService $bananaService,
    LemonService $lemonService,
    PearService $pearService,
    PeachService $peachService
    ){
        $this->appleService = $appleService;
        $this->bananaService = $bananaService;
        $this->lemonService = $lemonService;
        $this->pearService = $pearService;
        $this->peachService = $peachService;
    }
}

打字稿示例:

module namespace Test.Controllers {
    export class TestController{
        constructor(
        private appleService:Test.Services.AppleService,
        private bananaService:Test.Services.BananaService,
        private lemonService:Test.Services.LemonService,
        private pearService:Test.Services.PearService,
        private peachService:Test.Services.PeachService
        ){}
    }
}

是否有更好/更短的方法来做同样的事情,和/或是否有任何支持可以使即将发布的 PHP 版本更容易计划?

4

2 回答 2

0

还有一种替代方法,属性注入:

use DI\Annotation\Inject;

class TestController
{
    /**
     * @Inject
     * @var AppleService
     */
    private $appleService;
    /**
     * @Inject
     * @var BananaService
     */
    private $bananaService;
    /**
     * @Inject
     * @var LemonService
     */
    private $lemonService;
    /**
     * @Inject
     * @var PearService
     */
    private $pearService;
    /**
     * @Inject
     * @var PeachService
     */
    private $peachService;
}

是更短,还是更容易写?我让你判断。但我喜欢它,我最终不会得到一个臃肿的构造函数。这灵感来自 Java/Spring 仅供参考。

现在这个例子适用于PHP-DI(免责声明:我正在研究那个),但可能还有其他 DI 容器提供相同的功能。

警告:属性注入并不适合任何地方。

我发现它适用于控制器(因为控制器不应该被重用)。在这里阅读更多

我认为在服务中使用它是不合适的。所以这不是最终的解决方案。

于 2013-07-09T10:21:16.313 回答
0

这种语法糖最终将出现在 PHP 8.0(2020 年 11 月 26 日)中。

通过在构造函数中使用或前缀参数public,它们将被复制到并定义为具有相同名称的类属性。protectedprivate

在 PHP 8.0 中,OP 的例子可以写成:

namespace Test\Controllers;

use Test\Services\AppleService;
use Test\Services\BananaService;
use Test\Services\PearService;
use Test\Services\LemonService;
use Test\Services\PeachService;

class TestController{

   public function __construct(
       protected AppleService $appleService,
       protected BananaService $bananaService,
       protected LemonService $lemonService,
       protected PearService $pearService,
       protected PeachService $peachService
   ){
   }
}

https://wiki.php.net/rfc/constructor_promotion

https://stitcher.io/blog/constructor-promotion-in-php-8

于 2020-09-23T08:52:25.810 回答