实施服务

时间:2020-09-09 14:32:58

标签: php rest frameworks laminas-api-tools zend-servicemanager

我对Laminas API工具还很陌生,我想了解如何将服务正确地注入我的休息服务中。

示例:

namespace account\V1\Rest\Users;

use Laminas\ApiTools\DbConnectedResource;

class UsersResource extends DbConnectedResource {
    /**
     * Create a resource
     *
     * @param  mixed $data
     * @return ApiProblem|mixed
     */
    public function create($data) {
        $dataFiltered = $this->retrieveData($data);
        $this->table->createUser($dataFiltered);
        $id = $this->table->getLastInsertValue();
        $user = $this->fetch($id);
        // send email to user
        return $user;
    }

我需要在// send email to user中实现某些功能,才能调用下一个类的 send 方法


namespace account\Core\Mail;

class Mail {

    protected $service;
    protected $message;
    protected $body;

    public function __construct(MailgunService $service) {
        $this->service = $service;
        $this->message = new \Laminas\Mail\Message();
        $this->body = new \Laminas\Mime\Message();
    }

    private function updateBody() {
        $this->message->setBody($this->body);
    }

    public function addPart($part, $partType) {
        $mailPart = new \Laminas\Mime\Part($part);
        $mailPart->type = $partType;

        $this->body->addPart($mailPart);

        $this->updateBody();
    }

    public function setMessage($to, $from, $subj) {
        $this->message
                ->setTo($to)
                ->setFrom($from)
                ->setSubject($subj);
    }

    public function send() {
        $this->service->send($message);
    }

}

(Mail类具有如下所示的工厂(也可以使用UsersResource,但我不知道它是否重要))

namespace account\Core\Mail;

use Psr\Container\ContainerInterface;

class MailFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new Mail(
                $container->get(\SlmMail\Service\MailgunService::class)
                );
    }
}

我检查了laminas-servicemanager,但不知道如何进行操作,有任何提示吗?

1 个答案:

答案 0 :(得分:0)

如果我对您的理解正确,那么您想将服务注入到邮件类中吗?

那正是工厂的目的:

class Mail {

    protected $service;
    protected $anotherService // new service
    protected $message;
    protected $body;

    public function __construct(
        MailgunService $service,
        AnotherService $anotherService // new service
    ) {
        $this->service = $service;
        $this->anotherService = $anotherService; // new service
        $this->message = new \Laminas\Mail\Message();
        $this->body = new \Laminas\Mime\Message();
    }

// ... rest of class
}

然后在您的工厂中像这样注入服务:

class MailFactory
{
    public function __invoke(ContainerInterface $container)
    {
        return new Mail(
            $container->get(\SlmMail\Service\MailgunService::class),
            $container->get(AnotherService::class) // new Service
        );
    }
}

为此,ServiceManager需要了解新服务。并且应该使用MailFactory构建Mail类