zend framework 2 base path access in controller - zend-framework2

How can i call basePath helper in controller in ZF 2. I have to redirect to a particular url in which i need base path.
return $this->redirect()->toUrl($basePath.'/application/rent/search');

Here's an easy method to make all view helpers available from within the controllers. So you should be able to use the following:
public function someAction()
{
$renderer = $this->serviceLocator->get('Zend\View\Renderer\RendererInterface');
$url = $renderer->basePath('/application/rent/search');
$redirect = $this->plugin('redirect');
return $redirect->toUrl($url);
}

The full base url (http://...) can be determined from within the controller as follows:
$event = $this->getEvent();
$request = $event->getRequest();
$router = $event->getRouter();
$uri = $router->getRequestUri();
$baseUrl = sprintf('%s://%s%s', $uri->getScheme(), $uri->getHost(), $request->getBaseUrl());

try
class XxxController extends AbstractActionController
{
...
public function basePath()
{
$basePath = $this->serviceLocator
->get('viewhelpermanager')
->get('basePath');
return $basePath();
}
in
OR
public function algoAction()
{
echo $this->getRequest()->getBaseUrl();
}
http://project.com/profile
returns ""
http://localhost/~limonazzo/public/profile
returns /~limonazzo/public/

Related

Laravel Storage facade and retrieving files

How do I get files located in Storage?
I build a route and directed it to myCcontroller#myMethod. Method is below
public function myMethod()
{
$validPath = 'valid-path-inside-local-storage';
$file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath);
return $file;
}
But I get gibberish, probably raw data. How do I get the browser to display image if file is image or download it if file is, say, a.xls?
$validPath = 'valid-path-inside-local-storage';
$mimeType = Storage::mimeType($validPath);
$file = Storage::disk(env('STORAGE_TO_USE','local'))->get($validPath);
return (new Response($file, 200))
->header('Content-Type', $mimeType);
I hope I didn't miss anything.
For your route define this:
Route::get('docs/{file}', 'DocumentController#getDoc');
And this your controller
class DocumentController extends BaseController
{
public function getDoc($file){
$path = 'pathToDirectory/'.$file;
if(Storage::disk('yourDisk')->exists($path)){
$attachment = Storage::disk('yourDisk')->get($path);
$type = Storage::disk('yourDisk')->mimeType($path);
return Response::make($attachment, 200)->header("Content-Type", $type);
}else{
return Response::json('This file does not exists.');
}
}
}
You can use method response on the Storage facade.
public function myMethod()
{
$validPath = 'valid-path-inside-local-storage';
return Storage::disk(env('STORAGE_TO_USE','local'))->response($validPath);
}
This method return optimal response with file stream content and all needed headers: MIME type (Content-Type), filename (Content-Disposition) and file size (Content-Length).

Zend framework 2 session exists or not, in Module.php

I am trying to call the session in public function onBootstrap(MvcEvent $e) function in Module.php
public function onBootstrap(MvcEvent $e)
{
if( $user_session->offsetExists('user_email_id')){
//code here
}
else {
header("Location: ". $this->serverUrl() . "/register");
}
}
How can i achieve this?
i am not getting the echo $this->serverUrl(); inside the OnBootstrap function
There a number of problems with this code.
You need to create a new session container (Zend\Session\Container) to set/get your session data.
You are trying to set headers manually, although this would work, there are better ways to do so in ZF2.
Redirection in the onBootstrap method is probably not the best 'time' to do so.
You attempt to use a view helper in Module.php (\Zend\View\Helper\ServiceUrl) to redirect. View helpers can should only be called in the view. You can use them, however you would need to fetch it via the ViewPluginManager, rather than using $this->.
With these points in mind I would consider adding a event listener either late onRoute or early onDispatch.
For example:
namespace FooModule;
use Zend\ModuleManager\Feature\BootstrapListenerInterface;
use Zend\EventManager\EventInterface;
use Zend\Session\Container;
use Zend\Mvc\MvcEvent;
class Module implements BootstrapListenerInterface
{
public function onBootstrap(EventInterface $event)
{
$application = $event->getApplication();
$eventManager = $application->getEventManager();
$eventManager->attach(MvcEvent::EVENT_DISPATCH, [$this, 'isLoggedIn'], 100);
}
public function isLoggedIn(MvcEvent $event)
{
$data = new Container('user');
if (! isset($data['user_email_id'])) {
$serviceManager = $event->getApplication()->getServiceManager();
$controllerPluginManager = $serviceManager->get('ControllerPluginManager');
// Get the \Zend\Mvc\Controller\Plugin\Redirect
$redirect = $controllerPluginManager->get('redirect');
return $redirect->toRoute('some/route/path', ['foo' => 'bar']);
}
// use $data here
}
}

Render partial in other module ZF2

In my project I have to modules
Module1
Module2
In Module1 I have a view that needs to render a view that I have in Module2, so what I'm doing is:
$this->partial('partials/hello/title.phtml','Module2',array('data' => $data))
and seems I'm calling correctly the view, but inside of the view title.phtml I'm unable to use data
Undefined variable: data in /site/src/module/Module2/view/partials/hello/title.phtml
Do I need add something related to the configuration?
Thanks!
You aren't calling it correctly, try:
$this->partial('partials/hello/title.phtml', array('data' => $data));
See: http://framework.zend.com/manual/2.3/en/modules/zend.view.helpers.partial.html
The fact that the partial is in a different module doesn't matter. Having to specify the module name as the second parameter was a thing in ZF1 only.
Another solution is add your own view-path resolver in module-bootstrap:
class Module
{
/* #var \Zend\ServiceManager\ServiceManager $SM */
public static $SM;
/* #var \Zend\EventManager\EventManager $EM */
public static $EM;
public function onBootstrap(MvcEvent $e)
{
self::$SM = $e->getApplication()->getServiceManager();
self::$EM = $e->getApplication()->getEventManager();
//change view resolver to resolve views from {Module}/view/{Controller}/{Action}.phtml path
self::$EM->attach('dispatch', function($e) {
self::$SM->get('ViewRenderer')->resolver()->attach(
new \Engine\View\Resolver\MCA() , 10
);
});
}
....
Resolver gets a string, and must to return path or false (if not resolved), just write resolver to understand other-modules paths:
<?php
namespace Engine\View\Resolver;
use Zend\View\Renderer\RendererInterface as Renderer;
/**
* Resolves view scripts based on a stack of paths
*/
class MCA implements \Zend\View\Resolver\ResolverInterface
{
public function resolve($name, Renderer $renderer = null)
{
$path = explode('/', $name);
if (count($path)<3){
return false;
}
$module = array_shift($path);
$resolvedPath = ROOT_PATH . '/module/'. ucfirst($module) . '/view/' . implode('/', $path). '.phtml';
if (!file_exists($resolvedPath)){
return false;
}
return $resolvedPath;
}
}
There can be collisions, but you can regulate priority of resolvers (10 in example).

Get local value in layout or view in Zend Framework 2

How can we get local value (i.e: 'en' or 'en_US', 'de' etc) in layout.phtml or views in Zend Framework 2?
My local setting are exactly same as explained here
<?php
namespace FileManager;
use Zend\Mvc\ModuleRouteListener;
class Module
{
public function onBootstrap($e)
{
$translator = $e->getApplication()->getServiceManager()->get('translator');
$translator
->setLocale(\Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']))
->setFallbackLocale('en_US');
}
//...
}
I want to get local value something like this:
$locale = $this->translate()->getLocale(); // <-- It's not working anyway
I need to use '$locale' it while calling google map api url to get matched locale/language. I'm calling it throughtout the application in layout.phtml
$this->headScript()->appendFile('http://maps.googleapis.com/maps/api/js?language=' . $locale);
So I want to make language option dynamic while calling api.
PS: I don't have any query string parameter such as 'language', It's a google api thing which I need to set in script url (if you don't know) Please don't get confused.
Not answered here
Depends on where you want to get the Locale value from. In any case, you can do it in your controller, e.g.:
$locale = $this->request->getQuery('language');
$this->layout()->locale = $locale;
or
return new ViewModel(array('locale' => $locale));
Edit if you just want to get the locale from the translator, you can try this in view script:
$this->plugin('translate')->getTranslator()->getLocale();
My version is like that
<?php
namespace FileManager;
use Zend\Mvc\ModuleRouteListener;
use Zend\Session\Container;
class Module
{
public function onBootstrap($e)
{
$application = $e->getTarget();
$serviceManager = $application->getServiceManager();
$eventManager = $application->getEventManager();
$events = $eventManager->getSharedManager();
// session container
$sessionContainer = new Container('locale');
// test if the language in session exists
if(!$sessionContainer->offsetExists('mylocale')){
// doesn't so the browser lan
if(isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])){
$sessionContainer->offsetSet('mylocale', Locale::acceptFromHttp($_SERVER['HTTP_ACCEPT_LANGUAGE']));
}else{
$sessionContainer->offsetSet('mylocale', 'en_US');
}
}
// translation
$translator = $serviceManager->get('translator');
$translator ->setLocale($sessionContainer->mylocale)
->setFallbackLocale('en_US');
$mylocale = $sessionContainer->mylocale;
$events->attach('Zend\Mvc\Controller\AbstractActionController', 'dispatch', function($e) use ($mylocale) {
$controller = $e->getTarget();
$controller->layout()->mylocale = $mylocale;
}, 100);
}
//...
}
in your layout
$this->headScript()->appendFile('http://maps.googleapis.com/maps/api/js?language=' . $this->mylocale);

zf2 - How to override BjyAuthorize\View\RedirectionStrategy

How can I override the class RedirectionStrategy in *\vendor\bjyoungblood\bjy-authorize\src\BjyAuthorize\View\RedirectionStrategy.php in order to change the value of $redirectRoute attribute ?
http://pastebin.com/pPKsZcC5
First I follow this post : How to redirect to the login page with BjyAuthorize
Thank you!!
I found : https://github.com/bjyoungblood/BjyAuthorize/blob/master/docs/unauthorized-strategies.md
namespace MyApp;
use BjyAuthorize\View\RedirectionStrategy;
class Module
{
public function onBootstrap(EventInterface $e) {
$application = $e->getTarget();
$eventManager = $application->getEventManager();
$strategy = new RedirectionStrategy();
// eventually set the route name (default is ZfcUser's login route)
$strategy->setRedirectRoute('my/route/name');
// eventually set the URI to be used for redirects
$strategy->setRedirectUri('http://example.org/login');
$eventManager->attach($strategy);
}
}
It's works!
add in bjyauthorize.global.php
'unauthorized_strategy' => 'BjyAuthorize\View\RedirectionStrategy'
and then in module.php
use BjyAuthorize\View\RedirectionStrategy;
$strategy = new RedirectionStrategy();
$strategy->setRedirectRoute('zfcuser/login');
$eventManager->attach($strategy);

Resources