Zend move translator configuration from module.config.php to Module.php - zend-framework

I'm pretty new to ZF and have a question regarding translator configuration. I have an application with the following translator configuration inside the module.cofig file:
'translator' => [
'locale' => 'ru_RU',
'translation_file_patterns' => [
[
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
],
[
'type' => 'phparray',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.php',
],
],
'cache' => \Zend\Cache\StorageFactory::factory(
[
'adapter' => [
'name' => 'Filesystem',
'options' => [
'cache_dir' => APPLICATION_LOAD_PATH . '/data/cache',
'ttl' => '3600',
],
],
'plugins' => [
[
'name' => 'serializer',
'options' => [],
],
'exception_handler' => [
'throw_exceptions' => true,
],
],
]
),
],
This configuration works fine, but I want to know if is it possible to move this code inside Module.php trough the getTranslatorPluginConfig() . What I've tried is to use this method and return this same config:
public function getTranslatorPluginConfig(){
return [
'translator' => [
'locale' => 'ru_RU',
'translation_file_patterns' => [
[
'type' => 'gettext',
'base_dir' => __DIR__ . '/language',
'pattern' => '%s.mo',
],
[
'type' => 'phparray',
'base_dir' => __DIR__ . '/language',
'pattern' => '%s.php',
],
],
'cache' => \Zend\Cache\StorageFactory::factory(
[
'adapter' => [
'name' => Filesystem::class,
'options' => [
'cache_dir' => APPLICATION_LOAD_PATH . '/data/cache',
'ttl' => '3600',
],
],
'plugins' => [
[
'name' => 'serializer',
'options' => [],
],
'exception_handler' => [
'throw_exceptions' => true,
],
],
]
),
],
];
}
As you can see I haven't changed anything (except base_dir path). I don't get any errors, but the translator is not working at all. If you can tell me what are the steps I need to take to make this configuration work from the Module file and if this is possible at all, I'll be grateful. I don't expect plain code, but just a guidance/suggestion of what could be done, since all I find in the Zend documentation is related with making this configuration inside module.config. Thanks in advance.

Related

Laminas Cache config issue after updated to PHP 8.1 from zend3

I work on a project which is recently updated to Laminas and PHP 8.1 from Zend3 and PHP 7.4.
in config/autoload/global.php
'caches' => require __DIR__ . '/caches.php',
and this is caches.php
$cacheDefault = [
'adapter' => [
'name' => 'Memcached',
'options' => [
'servers' => Module::isRunningOnVM()
? ['127.0.0.1:11211']
: Module::getMemcachedServersFromEnvironment(),
],
],
];
return [
'cache_instrument_manager_search' => array_merge_recursive(
$cacheDefault,
[
'adapter' => [
'options' => [
'namespace' => 'instrument_manager_search',
'ttl' => 20,
],
],
]
),
'cache_weekly' => array_merge_recursive(
$cacheDefault,
[
'adapter' => [
'options' => [
'namespace' => 'weekly',
'ttl' => 604800, // whole week
],
],
]
),
];
It worked well in zend 3. but after updating to Laminas and PHP8.1 I got this error
Laminas\ServiceManager\Exception\ServiceNotCreatedException
File:
/project/vendor/laminas/laminas-servicemanager/src/ServiceManager.php:620
Message:
Service with name "cache_instrument_manager_search" could not be created. Reason: Configuration must contain a "adapter" key.
I have changed it to
return [
'cache_instrument_manager_search' => [
'adapter' => 'Memcached',
'options' => ['ttl' => 3600],
'plugins' => [
[
'name' => 'exception_handler',
'options' => [
'throw_exceptions' => false,
],
],
],
]
];
But Still has this error
Laminas\ServiceManager\Exception\ServiceNotFoundException
File:
/project/vendor/laminas/laminas-servicemanager/src/ServiceManager.php:557
Message:
Unable to resolve service "Memcached" to a factory; are you certain you provided it during configuration?
I need help. I read documents in Laminas but still could not solve this.
I'm using Redis Cache and I had to add:
'Laminas\Cache\Storage\Adapter\Redis'
to my modules.config.php file

Zend routing issue

I'm working on converting a (quite sloppily put together) zend expressive website to a zend framework 3 website for a local restaurant. When I set up the routing on the expressive website I would load a location based on a query parameter looking like this.
website.com/location?location=xxx
On my new website the routing looks like this
website.com/locations/view/xxx
I need to set up a route that redirects the old url to the new url. So far I have set up a route that looks for the
/location?location=[/:location]
hoping that it would recognize this 'Segment' route and load the appropriate LocationsController. Right now it is giving me a route not found error.
My code looks like below.
module.config.php
namespace Application;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'locations-old' => [
'type' => Segment::class,
'options' => [
'route' => '/location?location=[/:location]',
'defaults' => [
'controller' => Controller\LocationController::class,
'action' => 'index',
],
],
],
'locations' => [
'type' => Segment::class,
'options' => [
'route' => '/locations[/:action[/:location]]',
'constraints' => [
'action' => '[a-zA-Z]*',
'location' => '[a-zA-Z]*',
],
'defaults' => [
'controller' => Controller\LocationController::class,
'action' => 'index',
],
],
],
'locations.html' => [
'type' => Literal::class,
'options' => [
'route' => '/locations.html',
'constraints' => [
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'location' => '[a-zA-Z][a-zA-Z0-9_-]*',
],
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'about' => [
'type' => Literal::class,
'options' => [
'route' => '/about',
'defaults' => [
'controller' => Controller\AboutController::class,
'action' => 'index',
],
],
],
'employ' => [
'type' => Literal::class,
'options' => [
'route' => '/employ',
'defaults' => [
'controller' => Controller\EmployController::class,
'action' => 'index',
],
],
],
'news' => [
'type' => Literal::class,
'options' => [
'route' => '/news',
'defaults' => [
'controller' => Controller\NewsController::class,
'action' => 'index',
],
],
],
],
],
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
];
LocationController.php
namespace Application\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Application\Model\StoreTable;
use Zend\View\Model\ViewModel;
class LocationController extends AbstractActionController
{
private $table;
public function __construct(StoreTable $table)
{
$this->table = $table;
}
public function indexAction()
{
if($_GET['location'] && $this->table->doesExist($_GET['location'])) {
$location = $_GET['location'];
$this->redirect()->toRoute('locations', ['action' => 'view', 'location' => $location])->setStatusCode(302);
} else {
$this->redirect()->toUrl('/#locations')->setStatusCode(301);
}
}
public function viewAction()
{
$location = (string) $this->params()->fromRoute('location');
$store = $this->table->getStore($location);
return new ViewModel([
'store' => $store,
]);
}
}
Any help would be greatly appreciated and I can provide more info if needed.
Thanks!
configure your route as following, this will be handle query based url as you given "website.com/location?location=xxx",
In below route ":key" variable implies ?location=xxx
'locations-old' => [
'type' => Segment::class,
'options' => [
'route' => '/location/:key',
'defaults' => [
'controller' => Controller\LocationController::class,
'action' => 'index',
],
'constraints' => [
'key' => '[a-z0-9]+',
],
],
'child_routes' => [
'query' => ['type' => 'query'],
],
]

zf3 __construct() not working

I've created a module with name Commerce in zend 3 which is working fine. Now when I inject a dependency through __construct() it throws error
Too few arguments to function
Commerce\Controller\IndexController::__construct(), 0 passed in
/var/www/html/zf3/vendor/zendframework/zend-servicemanager/src/Factory/InvokableFactory.php
on line 30 and exactly 1 expected
Here is the controller code.
<?php
namespace Commerce\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Commerce\Model\Commerce;
class IndexController extends AbstractActionController
{
private $commerce;
/**
* IndexController constructor.
* #param Commerce $commerce
*/
public function __construct(Commerce $commerce)
{
$this->commerceModel = $commerce;
}
public function indexAction()
{
return new ViewModel();
}
}
module.config.php code
<?php
namespace Commerce;
use Zend\Router\Http\Literal;
use Zend\Router\Http\Segment;
use Zend\ServiceManager\Factory\InvokableFactory;
return [
'router' => [
'routes' => [
'home' => [
'type' => Literal::class,
'options' => [
'route' => '/',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
'commerce' => [
'type' => Segment::class,
'options' => [
'route' => '/commerce[/:action][/:id]',
'defaults' => [
'controller' => Controller\IndexController::class,
'action' => 'index',
],
],
],
],
],
'controllers' => [
'factories' => [
Controller\IndexController::class => InvokableFactory::class
],
],
'view_manager' => [
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => [
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'commerce/index/index' => __DIR__ . '/../view/commerce/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
],
'template_path_stack' => [
__DIR__ . '/../view',
],
],
];
Where is the issue? zend-di is already installed.
Your error is caused in line
Controller\IndexController::class => InvokableFactory::class
this does not provide a "Commerce\Model\Commerce" to the constructor of your IndexController. You need to change this to provide the dependency:
'controllers' => [
'factories' => [
Controller\IndexController::class => function($container) {
return new Controller\IndexController(
$container->get(\Commerce\Model\Commerce::class)
);
},
],
],
'service_manager' => [
'factories' => [
\Commerce\Model\Commerce::class => function($sm) {
/* provide any dependencies if needed */
/* Create the model here. */
return new \Commerce\Model\Commerce($dependencies);
},
]
],
The best approach is to provide its own factory for your Commerce\Model\Commerce class, as seen above in the setting 'factories' of 'service_manager'.
EDIT: as request, if you want to do everything inside the controller Factory, here is a simple example:
'controllers' => [
'factories' => [
Controller\IndexController::class => function($container) {
$dbAdapter = $container->get('Zend\Db\Adapter\Adapter');
$resultSetPrototype = new ResultSet();
$tableGateway = new TableGateway('commerceTableName', $dbAdapter, null, $resultSetPrototype);
return new Controller\IndexController(
new \Commerce\Model\Commerce($tableGateway)
);
},
],
],

yii2 always redirect to frontend/web

When i want to access to backend yii2 always redirect me to frontend.
Example:
I have installed the yii2-user (dektrium) module in frontend and backend and yii2-admin (mdm) module only in backend . And when i want to acess to
http://localhost/american_eshop/yii-application/frontend/web/**user/admin/index**"
yii2 in the first place accessing to this route and after redirect me to "http://localhost/american_eshop/yii-application/frontend/web/".
I.E. i can get access to resourse but it always redirect me and i cannot undestand where i am in my site.
Sorry for my poor english...
backend cofigs:
main.php
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-backend',
'basePath' => dirname(__DIR__),
'controllerNamespace' => 'backend\controllers',
'bootstrap' => ['log'],
'modules' => [],
'components' => [
'user' => [
'identityClass' => 'dektrium\user\models\User',
'enableAutoLogin' => true,
],
'authManager' => [
'class' => 'yii\rbac\DbManager'
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
'errorHandler' => [
'errorAction' => 'site/error',
],
],
'params' => $params,
];
main-local:
<?php
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'QuXcvHHNSiT3mEGgBln9c85IYF7uVkoU',
],
],
'modules' => [
'user' => [
'class' => 'backend\modules\user\Module',
'viewPath' => '#dektrium/user/views',
'enableUnconfirmedLogin' => true,
'confirmWithin' => 21600,
'cost' => 14,
'admins' => ['Admin']
],
]
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;
frontend:
main:
<?php
$params = array_merge(
require(__DIR__ . '/../../common/config/params.php'),
require(__DIR__ . '/../../common/config/params-local.php'),
require(__DIR__ . '/params.php'),
require(__DIR__ . '/params-local.php')
);
return [
'id' => 'app-frontend',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'frontend\controllers',
'components' => [
'user' => [
'identityClass' => 'dektrium\user\models\User',
'enableAutoLogin' => true,
],
'authManager' => [
'class' => 'yii\rbac\DbManager'
],
'log' => [
'traceLevel' => YII_DEBUG ? 3 : 0,
'targets' => [
[
'class' => 'yii\log\FileTarget',
'levels' => ['error', 'warning'],
],
],
],
'errorHandler' => [
'errorAction' => 'site/error',
],
'urlManager' => [
'enablePrettyUrl' => true,
'showScriptName' => false,
],
],
'params' => $params,
];
main-local:
<?php
$config = [
'components' => [
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'xlEFSbBB0pjvAJHtEOfY6r5BhDOTIAtB',
],
],
'modules' => [
'user' => [
'class' => 'frontend\modules\user\Module',
'viewPath' => '#dektrium/user/views',
'enableUnconfirmedLogin' => true,
'confirmWithin' => 21600,
'cost' => 14,
'admins' => ['Admin']
],
],
];
if (!YII_ENV_TEST) {
// configuration adjustments for 'dev' environment
$config['bootstrap'][] = 'debug';
$config['modules']['debug'] = 'yii\debug\Module';
$config['bootstrap'][] = 'gii';
$config['modules']['gii'] = 'yii\gii\Module';
}
return $config;

Cant use tockens and extrapattern together for REST services in Yii2

Yii2 REST query
I found this for using custom action in the controller for that i added the extrapattern mentioned in the above link
And its working fine when we search .but cant use the normal actions for the controller
'urlManager' => [
'enablePrettyUrl' => true,
'enableStrictParsing' => true,
'showScriptName' => false,
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'extraPatterns' => [
'GET search' => 'search'
],
'tokens' => [
'{id}' => '<id:\\w+>'
]
]
],
]
Regards
Thanks all
this solved my problem after lots of trying..
'rules' => [
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'extraPatterns' => [
'GET search' => 'search'
],
],
[
'class' => 'yii\rest\UrlRule',
'controller' => 'v1/country',
'tokens' => [
'{id}' => '<id:\\w+>'
]
],
],