Including settings in to module class - zend-framework

Im my module.config.php file got following excerpt:
return array(
'service_manager' => array(
'aliases' => array(
'Util\Dao\Factory' => 'modelFactory',
),
'factories' => array(
'modelFactory' => function($sm) {
$dbAdapter = $sm->get('Doctrine\ORM\EntityManager');
return new \Util\Dao\Factory($dbAdapter);
},
)
),
'doctrine' => array(
'driver' => array(
'application_entities' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(
__DIR__ . '/../src/Application/Model'
),
),
'orm_default' => array(
'drivers' => array(
'Application\Model' => 'application_entities'
)
),
),
),
How do i put the block "doctrine" in module class?

Well, this is actually fairly simple. Probably your Module class has the method getConfig(). That method usually loads moduleName/config/module.config.php.
So in whatever function you are, simply call the getConfig()-method. This is pure and basic php ;)
//Module class
public function doSomethingAwesome() {
$moduleConfig = $this->getConfig();
$doctrineConfig = isset($moduleConfig['doctrine'])
? $moduleConfig['doctrine']
: array('doctrine-config-not-initialized');
}
However you need to notice that this only includes your Modules config. If you need to gain access to the merged configuration, you'll need to do that in the onBootstrap()-method. Which would be done like this:
//Module class
public function onBootstrap(MvcEvent $mvcEvent)
{
$application = $mvcEvent->getApplication();
$serviceLocator = $application->getServiceLocator();
$mergedConfig = $serviceLocator->get('config');
$doctrineConfig = isset($mergedConfig['doctrine'])
? $mergedConfig['doctrine']
: array('doctrine-config-not-initialized');
}
This works similar if you're attaching to some events...

Related

Zend2 Module can't be initialized

Here my Module.php:
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* #link http://github.com/zendframework/ZendSkeletonModule for the canonical source repository
* #copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* #license http://framework.zend.com/license/new-bsd New BSD License
*/
namespace Users;
use Zend\ModuleManager\Feature\AutoloaderProviderInterface;
use Zend\Mvc\ModuleRouteListener;
class Module implements AutoloaderProviderInterface
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
// if we're in a namespace deeper than one level we need to fix the \ in the path
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function onBootstrap($e)
{
// You may not need to do this if you're doing it elsewhere in your
// application
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
}
}
And here my module.config.php:
<?php
return array(
'controllers' => array(
'invokables' => array(
'Users\Controller\Index' => 'Users\Controller\IndexController',
),
),
'router' => array(
'routes' => array(
'users' => array(
'type' => 'Literal',
'options' => array(
// Change this to something specific to your module
'route' => '/users',
'defaults' => array(
// Change this value to reflect the namespace in which
// the controllers for your module are found
'__NAMESPACE__' => 'Users\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
// This route is a sane default when developing a module;
// as you solidify the routes for your module, however,
// you may want to remove it and replace it with more
// specific routes.
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'users' => __DIR__ . '/../view',
),
),
);
But when I try to see the index page I get this:
( ! ) Fatal error: Uncaught
Zend\ModuleManager\Exception\RuntimeException: Module (Users) could
not be initialized. in
/var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php
on line 195
( ! ) Zend\ModuleManager\Exception\RuntimeException: Module (Users) could not be initialized. in /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/ModuleManager.php
on line 195
Anyone knows what's wrong with this code?
A couple of things to check:
The filename is Module.php - that exact case.
That Module.php is in module/Users (i.e. not in module/Users/src/)
I used internal server of php where I don't have xdebug enabled it got this:
127.0.0.1:48908 [500]: /public/ - Uncaught Zend\ModuleManager\Listener\Exception\InvalidArgumentException: Config being merged must be an array, implement the Traversable interface, or be an instance of Zend\Config\Config. boolean given. in /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/Listener/ConfigListener.php:342
Stack trace:
0 /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/Listener/ConfigListener.php(127): Zend\ModuleManager\Listener\ConfigListener->addConfig('Users', false)
1 [internal function]: Zend\ModuleManager\Listener\ConfigListener->onLoadModule(Object(Zend\ModuleManager\ModuleEvent))
2 /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(444): call_user_func(Array, Object(Zend\ModuleManager\ModuleEvent))
3 /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/EventManager/EventManager.php(205): Zend\EventManager\EventManager->triggerListeners('loadModule in /var/www/html/communicationapp/vendor/zendframework/zendframework/library/Zend/ModuleManager/Listener/ConfigListener.php on line 342

Zend framework 2 form element normalization

I am migrating an application from Zend 1 to Zend 2 and starting to desperate with one issue. The application works with different locales and therefore, I need to store the data in a normalized way in the database. In Zend 1 I used this code:
public function normalizeNumber( $value )
{
// get the locale to change the date format
$this->_locale = Zend_Registry::get('Zend_Locale' );
return Zend_Locale_Format::getNumber($value, array('precision' => 2, 'locale' => $this->_locale));
}
Unfortunately Zend 2 does not has this Zend_Locale_Format::getNumber any more and I was not able to figure out what function did replace it. I have tried with NumberFormat, but I get only localized data not normalized. I need this function to normalize data I receive from a form via POST. Can someone give some advice?
thanks
Just to complete my question. The Form element definition I am using is the following:
namespace Profile\Form;
use Zend\Form\Form;
use Zend\InputFilter\InputFilterProviderInterface;
class Profile Extends Form implements InputFilterProviderInterface
{
protected $model;
public function __construct( $model, $name = 'assignmentprofile')
{
parent::__construct( $name );
$this->setAttribute( 'method', 'post');
$this->model = $model;
...
$this->add( array(
'name' =>'CommutingRate',
'type' =>'Zend\Form\Element\Text',
'options' => array( // list of options to add to the element
'label' => 'Commuting rate to be charged:',
'pattern' => '/[0-9.,]/',
),
'attributes' => array( // Attributes to be passed to the HTML lement
'type' =>'text',
'required' => 'required',
'placeholder' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
...
'CommutingRate' => array(
'required' => true,
'filters' => array(
array( 'name' => 'StripTags', ),
array( 'name' => 'StringTrim'),
array( 'name' => 'NumberFormat', 'options' => array('locale' => 'en_US', 'style' => 'NumberFormatter::DECIMAL', 'type' => 'NumberFormatter::TYPE_DOUBLE',
))
),
'validators' => array(
array( 'name' => 'Float',
'options' => array( 'messages' => array('notFloat' => 'A valid numeric entry is required')),
),
),),
...
);
}
}
As mentioned before, I am able to localized the data and validate it in the localized manner, but i am failing to convert it back to a normalized manner...

ZF2 access to config in router configuration

i route by hostname and i want to get my domain name by local.php config file in config/autoload in zf2
i know how should i get configs in controller,
but i dont know how can i get it in my router configuration file
i comment what i want in my code
'router' => array(
'routes' => array(
'advertise' => array(
'type' => 'Hostname',
'options' => array(
'route' => 'www.myhome.com', // here i want to get my domain by config
'defaults' => array(
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index',
),
),
.............
You can use the API of the 'router' service (an instance of Zend\Mvc\Router\Http\TreeRouteStack) and add a route dynamically.
How you attach the route to the route stack is up to you, you could extend the default router factory Zend\Mvc\Service\RouterFactory with your own routes from config.
use MyModule\Mvc\Service;
use Zend\Mvc\Service\RouterFactory;
use Zend\ServiceManager\ServiceLocatorInterface;
class MyRouterFactory extends RouterFactory
{
public function createService(ServiceLocatorInterface $serviceLocator, $cName = null, $rName = null)
{
$serviceManager = $serviceLocator->getServiceLocator();
$router = parent::createService($serviceLocator, $cName, $rName);
$config = $serviceManager->get('config');
$router->addRoute('advertise', [
'type' => 'hostname',
'options' => [
'route' => $config['some_other_config_key'],
'defaults' => [
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index'
]
],
'priority' => 123
]);
return $router;
}
}
Remember to register it with the name Router in module.config.php to replace the default implementation.
'service_manager' => [
'factories' => [
'Router' => 'MyModule\Mvc\Service\MyCustomRouterFactory',
],
],
The nice thing with this approach is that the routers construction is all kept in one place; also as you are adding it with a factory class
you have access to other services should you need them.
Alternatively, you could add it via an event, although being triggered via the event manager, this method would likely be more resource intensive.
namespace MyModule;
use Zend\ModuleManager\InitProviderInterface;
use Zend\ModuleManager\ModuleManagerInterface;
use Zend\Mvc\Application;
use Zend\Mvc\MvcEvent;
class Module implements InitProviderInterface
{
// init is called when the module is initilised, we can use this to add a listener to the
// 'bootstrap' event
public function init(ModuleManagerInterface $manager)
{
$eventManager = $manager->getEventManager()->getSharedManager();
$eventManager->attach(Application::class, MvcEvent::EVENT_BOOTSTRAP, [$this, 'addRoutes']);
}
public function addRoutes(MvcEvent $event)
{
$serviceManager = $event->getApplication()->getServiceManager();
$router = $serviceManager->get('Router');
$config = $serviceManager->get('Config');
$router->addRoute('advertise', [
'type' => 'hostname',
'options' => [
'route' => $config['some_other_config_key'],
'defaults' => [
'controller' => 'Advertise\Controller\Advertise',
'action' => 'index'
]
],
'priority' => 123
]);
}
}

ZF2 Form: NumberFormat-filter with localization

hy,
how can I define the NumberFormat-filter for an input in a fieldset which is aware of the current locale? What I want is that numbers like 1000.33 are displayed in the view like this: 1.000,33 (or whatever locale is specified) I have tried it with the InputFilterProviderInterface, but it doesn't has any effect in the view:
<?php
namespace Customer\Form;
use Customer\Entity\OfferDay;
use DoctrineModule\Stdlib\Hydrator\DoctrineObject as DoctrineHydrator;
use Zend\Form\Fieldset;
use Zend\InputFilter\InputFilterProviderInterface;
class OfferDayFieldset extends Fieldset implements InputFilterProviderInterface
{
public function __construct($em)
{
parent::__construct('offerDayFieldset');
$this->setHydrator(new DoctrineHydrator($em))
->setObject(new OfferDay());
$this->add(array(
'name' => 'price',
'type' => 'Text',
'options' => array(
'label' => '',
),
));
}
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
),
),
),
),
);
}
}
In the view I output the input via the formRow()-function.
I also know that you can use the NumberFormat-Filter programmatically like this (l18n Filters - Zend Framework 2):
$filter = new \Zend\I18n\Filter\NumberFormat("de_DE");
echo $filter->filter(1234567.8912346);
// Returns "1.234.567,891"
but I wanna use the array-notation.
Has anybody done something like this or something similar?
ok this seems not as trivial as I thought :) but I got a solution.
first define the filter like this:
public function getInputFilterSpecification()
{
return array(
'price' => array(
'required' => false,
'filters' => array(
array(
'name' => 'NumberFormat',
'options' => array(
'locale' => 'de_DE',
'style' => NumberFormatter::DECIMAL,
'type' => NumberFormatter::TYPE_DOUBLE,
),
),
),
),
);
}
whereas locale is the currently used locale. This formats the numbers into the currect format before saving it to the database.
In the view, you can use the filter view helper to convert the numbers to the right format:
<?php
$this->plugin("numberformat")
->setFormatStyle(NumberFormatter::DECIMAL)
->setFormatType(NumberFormatter::TYPE_DOUBLE)
->setLocale("de_DE");
?>
<p>
<?php
$currentElement = $form->get('price');
$currentElement->setValue($this->numberFormat($currentElement->getValue()));
echo $this->formRow($currentElement);
?>
</p>
Result:
Database: 12.345 ->
View: 12,345 -> Database: 12.345

Zend Framework 2 - Gobal Variable that are accessible to controller/model that are initialize in local.php or global.php

Hello everyone please someone help me how to create a global variable in zend framework 2 to be use in table prefix that are accessible in controller and model.
Thanks and regards to all.
In your config/database.local.php you can define which you want globally
<?
return array(
'service_manager' => array(
'factories' => array(
//'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
'Zend\Db\Adapter\Adapter' => function ($serviceManager) {
$adapterFactory = new Zend\Db\Adapter\AdapterServiceFactory();
$adapter = $adapterFactory->createService($serviceManager);
\Zend\Db\TableGateway\Feature\GlobalAdapterFeature::setStaticAdapter($adapter);
return $adapter;
}
),
),
'db' => array(
'driver' => 'pdo',
'dsn' => 'mysql:dbname=testdb;host=localhost',
'username' => 'root',
'password' => '',
),
'msg' => array(
'add' => 'Data Inserted Successfully',
'edit' => 'Data Updated Successfully',
'delete' => 'Data Deleted Successfully',
),
);
?>
Controller File:
DemoController.php
<?php
namespace Demo\Controller;
use Zend\Mvc\Controller\AbstractActionController;
class DemoController extends AbstractActionController
{
public function indexAction($cms_page_name='whyus')
{
/*Call config file to fetch current cms page id-- fetch config file from database.local.php*/
$config = $this->getServiceLocator()->get('Config');
$all_msg = $config['msg'];
}
}
?>