Doron
Doron

Reputation: 3256

How do I generate an absolute url in a Zend Framework (1.11) controller action?

I have a facebook application.
Facebook says I need to redirect to a certain facebook url, in order for the user to give permissions to the application.

I currently have a view phtml file, with the following which works fine:

<script type="text/javascript">
top.location.href = 'https://www.facebook.com/dialog/oauth?client_id=<?php echo $this->fbAppId?>&redirect_uri=<?php echo $this->serverUrl() . $this->baseUrl() . $this->url(array('controller' => 'index', 'action' => 'post-authorize'))?>&scope=publish_stream,user_birthday,user_about_me,user_activities,user_location';
</script>

However - I want to try a different approach, that will save on resources and process time, by not rendering the view, and just redirecting via the Location header (using the redirector action helper, or any other action helper as such).

In the view script, I use the ServerUrl view helper, to generate an absolute path.
How can I generate an absolute path in the controller, without using a view helper ?
I don't see how using a view helper inside the controller is a good practice in the MVC pattern.

Notice: the redirect is made to facebook, where my own site url is appended as a get parameter. So the absolute url I need, is my own and not facebook. This means that using the setUseAbsoluteUri method will not help me, as it will work on the facebook url, and not mine.

Upvotes: 3

Views: 6144

Answers (2)

dinopmi
dinopmi

Reputation: 2673

Maybe you can have a look at the source code of the view helpers to get some "inspiration". For instance, Zend_View_Helper_BaseUrl uses the following:

Zend_Controller_Front::getInstance()->getBaseUrl();

And Zend_View_Helper_Url is using:

public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
{
    $router = Zend_Controller_Front::getInstance()->getRouter();
    return $router->assemble($urlOptions, $name, $reset, $encode);
}

Probably not as builtin as one would desire, but it's not a lot of code, so it could be helpful.

Hope that helps,

Upvotes: 1

Frederik Eycheni&#233;
Frederik Eycheni&#233;

Reputation: 1253

Using view helpers in your controller action won't render a view.

$redirectUri = $this->view->serverUrl() . $this->view->baseUrl() . $this->view->url(array('controller' => 'index', 'action' => 'post-authorize'))

$fbUrl = 'https://www.facebook.com/dialog/oauth?client_id='.$this->fbAppId.'&redirect_uri='.$redirectUri.'&scope=publish_stream,user_birthday,user_about_me,user_activities,user_location';

$this->_redirect($fbUrl);

The View object (not script) is initialized anyway in your controller, before even your action is called.

Upvotes: 5

Related Questions