ZF2 view plugin manager not merging config - php

On my module.config.php I've got something like:
return [
'view_helpers' => [
'invokables' => [
'mycustomviewhelper' => 'Namespace\View\Helper\MyCustomViewHelper',
],
],
];
I have also got a utility class that will handle the responsibility of rendering a helper. Something like Zend\Paginator.
Zend\Paginator has a __toString() method that proxies to render() call, which instantiates View\Renderer\PhpRenderer() and then calls $view->paginationControl($this).
I am trying to replicate the similar functionality in my utility class, which has similar strategy to what Zend\Paginator already does, the only thing being different is my view helper is a custom one. Hence, my code looks like:
$view->MyCustomViewHelper($this);
This does not work, because the PhpRenderer ignores the config defined manually and does the following in getHelperPluginManager:
$this->setHelperPluginManager(new HelperPluginManager());
I've tried invoking the helpers already defined in ViewHelperManager and this works well.
I did try merging in the config beforehand and then setting the PhpRenderer in the view but then this caused other problems, such as my partials were not found etc.
Now my question is why does ZF not consider any custom registered views when trying to render it in isolation. Is there any other way to do this?
Thank you.

Right, after a bit of a debugging, and playing with the configs, I was able to make this work. Still not sure if this is the best way to do this, but looks like currently there's no other way to make it work.
I created a factory for the utility class, instantiated the PhpRenderer, and then merged in my config with the ViewPluginManager manually. My factory now looks like:
public function createService(ServiceLocatorInterface $serviceLocatorInterface)
{
$dataTable = new DataTable;
$phpRenderer = new PhpRenderer();
$config = new \Zend\ServiceManager\Config([
'invokables' => [
'datatablerenderer' => 'DataTable\View\Helper\DataTableRenderer'
],
]);
$phpRenderer->setHelperPluginManager(new HelperPluginManager($config));
$dataTable->setView($phpRenderer);
return $dataTable;
}
However will have to refactor this so that the config comes from the view_helpers config key and is not hardcoded.

Related

execute global function automatically on running controller in yii2

We have web pages, where user will be redirected to $this->goHome(), if the session timeouts or user logouts. We have to destroy the all the session so, we have to add a function with destroying session. This function should be executed before running any action/controller in Yii2 i.e. similar to hooks in codeigniter. We have tried a helper function with destroying session and we have called the function as HomeHelper::getHelpDocUrlForCurrentPage(); in main.php layout, but the layout will be executed after running action in controller, it should work on running any controller as we have 100+ controllers. How this can be achieved, please suggest us in right way. Thanks in advance.
in
config/main.php
you could try using 'on beforeAction'
return [
'vendorPath' => dirname(dirname(__DIR__)) . '/vendor',
'bootstrap' => [
'log',
....
],
'on beforeAction' => function($event){
// your code ..
} ,
'modules' => [
....
],
...
];
While #ScaisEdge solution would work I believe application config is not proper place to hold application logic.
You should use filters to achieve result you want.
First you need to implement filter with your logic. For example like this:
namespace app\components\filters;
class MyFilter extends yii\base\ActionFilter
{
public function beforeAction() {
// ... your logic ...
// beforeAction method should return bool value.
// If returned value is false the action is not run
return true;
}
}
Then you want to attach this filter as any other behavior to any controller you want to apply this filter on. Or you can attach the filter to application if you want to apply it for each action/controller. You can do that in application config:
return [
'as myFilter1' => \app\components\filters\MyFilter::class,
// ... other configurations ...
];
You might also take a look at existing core filters if some of them can help you.

zf3 change locale depending on user selection

I have Zend Framework 3 Application with working translator using po files.
I have configured it like this in my \config\global.php file:
'translator' => [
'locale' => 'en_US',
'translation_file_patterns' => [
[
'type' => 'gettext',
'base_dir' => getcwd() . '/data/language/',
'pattern' => '/%s/general.mo',
],
],
],
When i change the value of the "locale" it works ok and finds the proper .po file.
I need to be able to set the locale depending on a user profile's value saved in the database.
I have checked the documentation from here http://zendframework.github.io/zend-i18n/translation/ and the tutorial from here https://docs.zendframework.com/tutorials/i18n/ but they just mention the setLocale() method with no explanation or example. There is similar thread here Zend framework 2 : How to set locale globaly? but it's for ZF2 and it doesn't provide working solution just some suggestions.
To summarize my question - how and where should i use the setLocale() method so it would be effective in the whole application and $this->translate($message) in all view files will use the new locale instead the default one used in the configuration file?
You just need to set the PHP locale. To do so, use \Locale::setDefault('en-GB');.
Have a look at SlmLocale, this specific file is where it's done.
While that was the easiest way, you could also use the setLocale function on the MvcTranslator I guess. For that, you would need to override the existing factory with your own factory, therefore decorating the original one.
If you look at the ConfigProvider file in zend-mvc-i18n, you can see that aliases and factories are used here to create the MVC translator. Then you can see how the factory in question works, it basically creates a decorate translator, as stated in the doc.
By default, the service manager always provide the same instance (shared service), just like a singleton.
What we will therefore do is override this configuration (ie. make sure your own module is after the Zend\Mvc\I18n in modules.config.php). Then, in the module configuration, we can provide our own translator.
Our translator basically consist of the translator from the documentation, on which the setLocale is called. In order to do so, we can use a delegator.
return [
'factories' => [
TranslatorInterface::class => TranslatorServiceFactory::class,
],
'delegators' => [
TranslatorInterface::class => [
\Application\Factory\TranslatorFactory::class,
],
],
];
And then the TranslatorFactory:
use Interop\Container\ContainerInterface;
use Zend\ServiceManager\Factory\DelegatorFactoryInterface;
class TranslatorFactory implements DelegatorFactoryInterface
{
public function __invoke(ContainerInterface $container, $name, callable $callback, array $options = null)
{
$translator = call_user_func($callback);
$translator->setLocale('en-GB');
return $translator;
}
}
That would be one way to do it (you get the container in that factory, so you could get some user data probably).
Another solution is to use the event system, and only declare the locale in the event listener where you retrieve your user details.

Loading core scripts such as jQuery in Yii 2

I've been having a hard time trying to figure out how to load jQuery or other CORE scripts in Yii 2.
In Yii 1 it seemed this was the way:
<?php Yii::app()->clientScript->registerCoreScript("jquery"); ?>
In Yii 2, $app is a property of Yii, not a method, so the above naturally doesn't work, but changing it to:
<?php Yii::$app->clientScript->registerCoreScript("jquery"); ?>
produces this error:
Getting unknown property: yii\web\Application::clientScript
I couldn't find any documentation for Yii 2 about loading core scripts, so I tried the below:
<?php $this->registerJsFile(Yii::$app->request->baseUrl . '/js/jquery.min.js', array('position' => $this::POS_HEAD), 'jquery'); ?>
Whilst this loads jQuery in the head, a second version of jQuery is also loaded by Yii when needed and hence causes conflict errors.
Additionally, I don't want to use Yii's implementation of jQuery, I would prefer to maintain my own and hence that is why I am doing this.
How can I load jQuery and other core files without Yii loading duplicate copies of them when it needs them?
In order to disable Yii2's default assets you can refer to this question:
Yii2 disable Bootstrap Js, JQuery and CSS
Anyway, Yii2's asset management way is different from Yii 1.x.x. First you need to create an AssetBundle. As official guide example, create an asset bundle like below in ``:
namespace app\assets\YourAssetBundleName;
use yii\web\AssetBundle;
class YourAssetBundleName extends AssetBundle
{
public $basePath = '#webroot';
public $baseUrl = '#web';
public $css = [
'path/file.css',//or files
];
public $js=[
'path/file.js' //or files
];
//if this asset depends on other assets you may populate below array
public $depends = [
];
}
Then, to publish them on your views:
use app\assets\YourAssetBundleName;
YourAssetBundleName::register($this);
Which $this refers to current view object.
On the other hand, if you need to only register JS files into a view, you may use:
$this->registerJsFile('path/to/file.js');
yii\web\View::registerJsFile()
And if you need to only register CSS files into a view, you may use:
$this->registerCssFile('path/to/file.css');
yii\web\View::registerCssFile()
You can remove the core jQuery from loading like so:
config/web.php
'assetManager' => [
'bundles' => [
// you can override AssetBundle configs here
'yii\web\JqueryAsset' => [
'sourcePath' => null,
'js' => []
],
],
],

Phalcon router doesn't react to subfolders and namespace declaration

So I've been reading a ton of stackoverflow and phalcon forum threads.. (I'm starting to hate this framework), but nothing seem to work and it doesn't explain why like Laravel does, for example.
I'm just trying to be able to operate with this application structure:
As you can see, all I want is to use namespaced controllers in subfolders to make more order for my code.
According to all explanations, here's my loader.php:
<?php
$loader = new \Phalcon\Loader();
/**
* We're a registering a set of directories taken from the configuration file
*/
$loader->registerDirs(
array(
$config->application->controllersDir,
$config->application->modelsDir,
$config->application->pluginsDir
)
)->register();
AFAIK, Phalcon should traverse all subfolders for not found classes when used via registerDirs.
Then I define my routes to specific controller after the main route to index controllers in base directory:
<?php
$router = new Phalcon\Mvc\Router(false);
$router->add('/:controller/:action/:params', array(
'namespace' => 'App\Controllers',
'controller' => 1,
'action' => 2,
'params' => 3,
));
$router->add('/:controller', array(
'namespace' => 'App\Controllers',
'controller' => 1
));
$router->add('/soccer/soccer/:controller', array(
'namespace' => 'App\Controllers\Soccer',
'controller' => 1
));
$router->add('/soccer/:controller/:action/:params', array(
'namespace' => 'App\Controllers\Soccer',
'controller' => 1,
'action' => 2,
'params' => 3
));
return $router;
And one of my controllers look like:
<?php namespace App\Controllers\Soccer;
use App\Controllers\ControllerBase as ControllerBase;
class IndexController extends ControllerBase
{
public function indexAction()
{
}
}
What's wrong here? Default top namespace is not registered? Am I missing something?
This just doesn't work. When I try to open myserver.com/soccer which I expect to go to app/controllers/soccer/IndexController.php, but instead it tells me:
SoccerController handler class cannot be loaded
Which basically means it's looking for SoccerController.php in /controllers directory and totally ignores my subfolder definition and routes.
Phalcon 1.3.0
Stuck on this for a week. Any help - Much appreciated.
I was having a problem with loading the ControllerBase and the rest of the controllers in the controllers folder using namespaces. I was having a hard time since other example projects worked fine and I realized that I was missing a small detail in the despatcher declaration where I was supposed to setDefaultNamespace
(ref: https://github.com/phalcon/vokuro/blob/master/app/config/services.php)
$di->set('dispatcher', function () {
$dispatcher = new Dispatcher();
$dispatcher->setDefaultNamespace('App\Controllers');
return $dispatcher;
});
or you can specify it directly on the routing declaration file like this
$router->add("/some-controler", array(
'namespace' => 'App\Controllers'
'controller' => 'some',
'action' => 'index'
));
that should work as well, it might be a bit confusing at first with namespaces but once you get a hang of it you will love this extremely fast framework
It looks like your namespaces have capitals
App\Controllers\Soccer
and your folder structure does not
app\controllers\soccer
In my app I have controllers with a namespace and I have just tried changing the case of the folders so they don't match and I get the missing class error.
Of course it does raise a question, how many controllers are you planning on having that namespacing them is worthwhile? Are you grouping controllers and action by function or content? I used to have loads of controllers in Zend, but now I have grouped them by function I only have 16 and I am much happier. e.g. I suspect soccer, rugby, hockey etc will probably be able to share a sport controller, articles, league positions etc will have a lot of data in common.
ps Don't give up on Phalcon! In my experience it is sooo much faster than any other PHP framework I have used it is worth putting up with a lot :)
Are you sure Phalcon traverses subfolders when registering directories to the autoloader? Have you tried adding a line to your autoloader which explicitly loads the controllers\soccer directory?
Alternatively, if your soccer controller is namespaced, you can also register the namespace: "App\Controllers\Soccer" => "controllers/soccer/" with the autoloader.

Can the process of creating an module in zf2 be shortend?

I am looking at a few tutorials and to just create 1 module you have to modify a bunch of configuration files in order to make the controllers, models, and views work. I see this as impossible to try and remember it all or comprehend what it is I’m doing. Is there an alternative method that creates these for me? so that i don’t have to write it all out every time i create a controller, or a module etc. I honestly don’t see how this is faster. I come from a codeigniter background so making this switch has me banging my head against the wall multiple times trying to comprehend.
I've been using ZF2 for a few months now, and I've found that writing a class to generate that config for you is helpful.
There is no tool out there to do that for you. But if you follow the following approach, you should come right quite quickly:
class Configurator {
public static function route($name, $url, $controller, $action='index') {
return array(
'router' => array(
...
),
);
}
# Other static configuring methods
...
}
Then in your config you use the Configurator like this:
use Configurator;
return array_merge_recursive(
array(
'view_manager' => array(
...
),
),
# Other top-level config
...
Configurator::route('home', '/', 'Application\Controller\Index'),
Configurator::route('other', '/other', 'Application\Controller\Other')
);
Your config is deep-merged by array_merge_recursive, utimately producing the config you want with your own custom-built generators. You're at liberty to configure whole sets of config with one method, so you can create a resource configurator which sets up the controller invokables, the routes, and anything else required in one method.
array_merge_recursive FTW!
Enjoy! :)

Categories