【问题标题】:How use URL ZF2 in my Entity Class如何在我的实体类中使用 URL ZF2
【发布时间】:2014-04-13 11:00:28
【问题描述】:

我必须在发送给我的用户的电子邮件中插入一个链接。所以我有一个发送这封邮件的实体类。但我不知道如何使用 ZF2 的视图/控制器系统的“url”方法创建此链接。

我的班级是:

class UserEntity
{
  public function sendMail($user)
  {
      $link = $unknow->url("route",array("param" => "param")); //how can create this ? 
      $text = "click here $link";
      $this->sendMail($to,$text);
  }
}

你能帮帮我吗?谢谢

【问题讨论】:

  • 这是一个非常非常错误的地方做这样的事情。实体是数据对象,(几乎)仅此而已。最好将其外包到服务中,并通过 ViewHelperManager 注入 URL ViewHelper。

标签: url hyperlink frameworks zend-framework2


【解决方案1】:

在设计方面,considered bad practice 让您的域模型负责创建 URL(或任何其他不以最简单的术语描述实体的内容)。

我将创建一个 UserService 来封装 SendMail 函数,其中 UserEntity 可以作为参数传递,它是用于发送电子邮件的 email 属性。

class UserService {

   protected $mailService;

   public function __construct(MailService $mailService) {
      $this->mailService = $mailService;
   }

   public function sendUserEmail(UserEntity $user, $message) {

      $this->mailService->send($user->getEmail(), $message);
   }  
}

邮件服务可以是另一个封装Zend\Mail\Transport 实例的服务。

您的控制器将使用UserService 将邮件发送给正确的用户。

$message 需要包含使用 the Zend\Mvc\Controller\Plugin\Url controller plugin 生成的 URL

class UserController extends AbstractActionController {
   protected $userService;

   public function __construct(UserService $userService) {
     $this->userService = $userService;
   }  

   public function sendEmailAction() {
     // load $user from route params or form post data
     $user = $this->userService->findUserByTheirId($this->params('id'));         

     // Generate the url
     $url = $this->url()->fromRoute('user/foo', array('bar' => 'param1'));
     $message = sprintf('This is the email text <a href="%s">link</a>!', $url); 

     $this->userService->sendUserEmail($user, $message);
   }
}

这些都是人为的例子,但我的观点是,你应该只在你的实体中存储信息,让你“做事”它,而不是它。 p>

【讨论】:

  • 感谢您的回答。因此,例如,如果我想发送邮件以验证用户的邮件地址,我应该在我的控制器中写下这个: public function registrationAction() { if ($this->userService->addUser($data)){ $this-> sendMail($data->user_email); } } 公共函数 sendMail($email) { $url = $this->url()->fromRoute("verifyLink"); $text = "要验证您的地址,请单击此处 $url"; $this->userService->sendMail($email,$text); }
  • 看起来不错;请记住,我的示例不包括常规验证,因此当您从用户那里获取电子邮件地址时,您应该使用经过正确验证的表单数据 $form-&gt;isValid() == true,然后创建用户实体并发送电子邮件或您需要的任何内容。跨度>
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-02-01
  • 1970-01-01
  • 2023-04-11
  • 2015-12-25
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多