Zend Framework website.com/username - zend-framework

One of the application I am developing using Zend Framework requires the user's profile page to be accessed via website.com/username, while other pages should be accessed by website.com/controller_name/action_name
I am not too sure how can this be achieved, however, I feel this can be done with some tweaks in the .htaccess file.
Can someone here please help me out?
Many thanks in advance

As suggested before, you can use a custom route that will route single level requests. However, this will also override the default route. If you're using modules, this will no longer work example.com/<module>.
I have done this before but only for static pages. I wanted this:
example.com/about
instead of this:
example.com/<some-id>/about
while maintaining the default route so this still works
example.com/<module>
example.com/<controller>
The way I did this was using a plugin to test if my request could be dispatched. If the request could not be dispatched using the default route, then I would change the request to the proper module to load my page. Here is a sample plugin:
class My_Controller_Plugin_UsernameRoute extends Zend_Controller_Plugin_Abstract
{
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
$dispatcher = Zend_Controller_Front::getInstance()->getDispatcher();
if (!$dispatcher->isDispatchable($request)) {
$username = $request->getControllerName();
$request->setModuleName('users');
$request->setControllerName('dashboard');
$request->setActionName('index');
$request->setParam('username', $username);
/** Prevents infinite loop if you make a mistake in the new request **/
if ($dispatcher->isDispatchable($request)) {
$request->setDispatched(false);
}
}
}
}

What about using Zend_Controller_Router_Route, look here the link http://framework.zend.com/manual/en/zend.controller.router.html#zend.controller.router.routes.standard.variable-requirements

Related

Importing CURL into block in Magento 2

I have a custom block that needs to request data from an external API.
Examples refer to a construct like this:
class CustomerBalance extends \Magento\Framework\View\Element\Template
{
public function __construct(
\Magento\Framework\HTTP\ZendClientFactory $httpClientFactory
)
But that breaks the site and the page fails to load correctly without logging any errors.
I have the same problem trying to use GuzzleHttp when I import that.
I guess there is something I'm missing about Magento 2 importing...
Or is there another way to access the Magento curl object?
Any help would be appreciated.
It appears I was simply importing the wrong class. This works:
protected $_httpAdapter;
public function __construct(
\Magento\Framework\HTTP\Adapter\Curl $httpAdapter
){
$this->_httpAdapter = $httpAdapter;
}
A more complete answer can be found here:
https://magento.stackexchange.com/questions/153993/magento-2-curl-send-header-with-response

using action helpers in Zend Framework 1.8

Hi am starting off with Zend Framework and have a question about action helpers. My first application is a simple authentication system (following a tutorial from a book). The registration and authentication seems to work fine but the redirect doesn't.
I have a customer controller that has this among others:
class CustomerController extends Zend_Controller_Action
{
// some code here......
public function authenticateAction()
{
$request = $this->getRequest();
if (!$request->isPost()) {
return $this->_helper->redirector('login');
}
// Validate
$form = $this->_forms['login'];
if (!$form->isValid($request->getPost())) {
return $this->render('login');
}
if (false === $this->_authService->authenticate($form->getValues())) {
$form->setDescription('Login failed, please try again.');
return $this->render('login');
}
return $this->_helper->redirector('index');
}
the authenticate url is http://localhost/customer/authenticate and this seems to work fine but it does not redirect. After authentication I get a blank page which looks like its taking me to the index and just sits there. I tried using '/index' instead but that did not help either. Do I need to do anything special to make the redirector helper work? I have a logout action which behaves the same.
You should call
$this->_helper->redirector('index');
without the return.
I found out there may be a problem with my setup. The code above is perfect, works on another computer.

Redirect in Front Controller plugin Zend

I'm trying to centralise my redirects (based on authentication and various other states) into a front controller plugin. So far I've tried:
$this->setRequest(new Zend_Controller_Request_Http('my_url'));
at various points in the plugin (i.e. from routeStartup to dispatchLoopShutdown) and also:
$this->setResponse(new Zend_Controller_Response_Http('my_url'));
Can anyone offer some assistance on this, or point me in the direction of a tutorial?
The easiest way would be to use ZF's Redirect ActionHelper
$r = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
$r->gotoUrl('/some/url')->redirectAndExit();
Alternatively instantiate it without the HelperBroker
$r = new Zend_Controller_Action_Helper_Redirector;
$r->gotoUrl('/some/url')->redirectAndExit();
The ActionHelper provides an API solely concerned about redirecting through a number of methods, like gotoRoute, gotoUrl, gotoSimple, which you can use depending on your desired UseCase.
Internally, the ActionHelper uses the APIs of Response and Router to do the redirect though, so you can also use their methods directly, e.g.
$request->setModuleName('someModule')
->setControllerName('someController')
->setActionName('someAction');
or
$response->setRedirect('/some/url', 200);
Further reading:
http://devzone.zend.com/article/3372-Front-Controller-Plugins-in-Zend-Framework
http://framework.zend.com/manual/en/zend.controller.actionhelpers.html
http://framework.zend.com/manual/en/zend.controller.response.html
http://framework.zend.com/manual/en/zend.controller.plugins.html
http://framework.zend.com/apidoc/core
http://framework.zend.com/svn/framework/standard/trunk/library/Zend/Controller/
If you are looking to redirect if the user is not logged it, the first parameter of dispatchLoopStartup() is a handle to the request object.
public function dispatchLoopStartup(Zend_Controller_Request_Abstract $request)
{
if(!Zend_Auth::getInstance()->hasIdentity())
{
$request->setControllerName('auth');
$request->setActionName('login');
// Set the module if you need to as well.
}
}
If you want to redirect in the index page then this should suffice.
public function preDispatch(Zend_Controller_Request_Abstract $request)
{
if(!Zend_Auth::getInstance()->hasIdentity())
{
$baseUrl = new Zend_View_Helper_BaseUrl();
$this->getResponse()->setRedirect($baseUrl->baseUrl());
}
}
If you want to redirect somewhere else then just change the parameter in the setRedirect() function
Thanks!
:)

Zend Framework: How to disable default routing?

I've spent many hours trying to get this to work. And I'm getting quite desperate.
Would be great if someone out there could help me out :)
Currently using Zend Framework 1.9.5, though I have been struggling to get this to work for many versions now.
What I want to do is provide my own routes through an XML config, and make sure that everything that is not defined in my config will end up on my errorController.
(preferably in a way so I can em apart from EXCEPTION_NO_CONTROLLER and EXCEPTION_NO_ACTION)
I figured that this means I have to get rid of default /:module/:controller/:action and /:controller/:action routes.
So when I tell the router to removeDefaultRoutes(), it won't match these default routes anymore. But now the router is now routing every unrouted route to the defaultcontroller::defaultaction (What the ??)
$front->getRouter()->removeDefaultRoutes();
So, anyone know how to make the frontcontroller (or a part of it) throw an exception when an URI can not be routed?
Reason I want to do this is to prevent duplicate content, and have better 404 pages (in this case, no controller / no action errors are actually application errors instead of not-found)
did you try adding a new route like
$route = new Zend_Controller_Router_Route('*', array('controller'=>'error', 'module'=>'default', 'action'=>'error'));
$router->addRoute('default', $route);
You need to add this route first as it needs to be the last processed.
Fast forward in time to one year later... (time travel music)
Here's another way that I think is much less "intrusive". You can write a plugin to catch the default route and when that happens just throw an exception which at the end of the whole cycle gets translated into a 404 by the front controller.
class Application_Plugin_DisableDefaultRoutes extends Zend_Controller_Plugin_Abstract
{
public function routeShutdown(Zend_Controller_Request_Abstract $request)
{
$front = Zend_Controller_Front::getInstance();
$currentRoute = $front->getRouter()->getCurrentRouteName();
if ($currentRoute == 'default') {
throw new Exception('Default route is disabled');
}
}
}
You can load your plugin in Bootstrap.php
protected function _initPlugins()
{
$front = Zend_Controller_Front::getInstance();
$front->registerPlugin(new Application_Plugin_DisableDefaultRoutes());
}
With this way you can load the plugin in the production machine and leave it out in development where you might want to use the default route for quick tests or something else.

How to access URL parameters in bootstrap

I'm trying to capture a URL parameter in my bootstrap file but after several attempts I'm not able to do it.
I've tried this but it does not work:
protected function _initGetLang() {
$frontController = Zend_Controller_Front::getInstance();
$lang= $frontController->getParam('lang');
}
Is this the right way to do it?
Thks.
You won't be able to access the request params from the bootstrap because it hasn't yet gone through the dispatch/routing process. I think you'd be better served by using a Controller Plugin, performing actions based on the URL is what they do best. Or if you absolutely have to do it in the bootstrap, getRequestUri() or $_GET is available, or you could write a quick script to parse the url yourself.
Edit:
I've done some silly stuff like this in the past before I figured out how plugins work:
/**
* Grab the module name without a request instance
*
* #return string The module name
*/
public static function getModuleName()
{
$uri = ltrim($_SERVER["REQUEST_URI"], "/");
$module = substr($uri, 0, strpos($uri, "/"));
return $module;
}
This would at least give you a module name that you could switch on in the bootstrap. You should be able to do anything you need with the plugins done correctly though.