LionAlex
LionAlex

Reputation: 23

How use URL ZF2 in my Entity Class

I must insert a link in an email that send to my user. So I have an Entity class that send this mail. But I don't know how i can create this link with "url" method of the view/controller system of ZF2.

My class is:

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);
  }
}

Can you help me? Thanks

Upvotes: 0

Views: 216

Answers (1)

AlexP
AlexP

Reputation: 9857

In terms of design, it would be considered bad practice to have your domain model responsible for the creation of the URL (or anything else that that does not describe the entity in its simplest terms).

I would create a UserService that would encapsulate the a SendMail function where a UserEntity could be passed as an argument and it's email property used to send the 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);
   }  
}

The mail service could be another service encapsulating the Zend\Mail\Transport instances.

Your controller would use the UserService to send the mail to the correct user.

The $message which needs to include a URL that is generated using the Zend\Mvc\Controller\Plugin\Url controller plugin

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);
   }
}

These are contrived examples but my point is that you should only store information in your entity allowing you to "do stuff" with it, not within it.

Upvotes: 2

Related Questions