Search code examples
urlzend-framework2email-validationservice-layer

baseurl in Service layer of zend framework 2


i am trying to implement service layer in my application. But i am facing problem while, when i am send mail from service layer to user.

Problem:

I am trying to send email confirmation from service layer, which include path of my website like

<a href="www.mysite.com/email-confirmation/email/verificationToken">Click Here to verify your account</a>

how can i create link in service mail ? I see this the below example in someone's controller, but how can i do this service layer?

->setBody("Please, click the link to confirm your registration => " .
                    $this->getRequest()->getServer('HTTP_ORIGIN') .
                    $this->url()->fromRoute('auth-doctrine/default', array(
                        'controller' => 'registration',
                        'action' => 'confirm-email',
                        'id' => $user->getUsrRegistrationToken())));

Solution

  • If your Service Layer is similar to a Model file, then add below lines of code to the Service Layer class file -

    protected $router;
    protected $request;
    
    public function setRouter($router = null) {
        $this->router = $router;
    }
    
    public function getRouter() {
        return $this->router;
    }
    
    public function setRequest($request = null) {
        $this->request = $request;
    }
    
    public function getRequest() {
        return $this->request;
    }
    

    Now from the Controller class, when your using the Service Layer class, do similar to the following - (It may not be exactly the same but you will get the idea)

    Controller Class -

    $service_layer_classname = new ServiceLayer_ClassName();
    $service_layer_classname->setRequest($this->getRequest());
    $service_layer_classname->setRouter($this->getEvent()->getRouter());
    

    In this way, you can use similar functions to get the Controller based access in the Service Layer Class.

    OR

    in a short but not-recommended way, you can just pass the whole controller object (i.e. $this) to the Service Layer class and access all the functions. Obviously it is not a good programming approach.

    I hope it helps.