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

Answers


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.


Need Your Help

Use SMS Emulator from Android Test Case

android unit-testing continuous-integration sms emulation

I want to automate functional testing of my code which works with SMS. I know, that I can use send sms command and sms will be sent to emulator instance.

Foreign key reference to a two-column primary key

sql schema primary-key

I'm building a database that must work on MySQL, PostgreSQL, and SQLite. One of my tables has a two-column primary key: