doctrine-extensions Uploadable, how to use in Zend Framework 2? - upload

I integrated doctrine-extensions in my project. Timestampable is working as example. But how to use the "Uploadable"-behavior?
I read this doc. They're writing in the usage-part about using $listener, but how do i get this variable? in my Controller or Service? Where does it come from?
thanks for any advice...

Finally, got it...:
instead of:
'doctrine' => array(
'eventmanager' => array(
'orm_default' => array(
'subscribers' => array(
'Gedmo\Uploadable\UploadableListener',
//...
),
),
),
'driver' => array(
// ...
),
),
use this: register the uploadable listener through the servicemanager:
'doctrine' => array(
'eventmanager' => array(
'orm_default' => array(
'subscribers' => array(
'doctrine_extensions.uploadable',
//...
),
),
),
'driver' => array(
// ...
),
),
'service_manager' => array(
'invokables' => array(
'doctrine_extensions.uploadable' => 'Gedmo\Uploadable\UploadableListener'
)
),
then in the controller as example, it works like this:
$uploadManager = $this->getServiceLocator()->get('doctrine_extensions.uploadable');
foreach($this->getRequest()->getFiles()->toArray() as $file) {
$entity = new MyEntity();
$uploadManager->addEntityFileInfo($entity, $file);
// persist($entity) ...
}

Related

ZF2: Zend Framework 2.3.0: Fatal Error: class IndexController not found

I'm studying the Zend Framework by building a tutorial application.
I've checked my code a couple of times comparing it to the source code
of the book.
I can't come up with a solution or explanation as to why
this error keeps occuring. Can anyone help me out?
Fatal error: Class 'Wall\Controller\IndexController' not found in C:\xampp\htdocs\Connect\client\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php on line 170
Call Stack
# Time Memory Function
1 0.0010 138824 {main}( ) ..\index.php:0
2 0.1250 4071920 Zend\Mvc\Application->run( ) ..\index.php:12
3 0.1260 4090064 Zend\EventManager\EventManager->trigger( ) ..\Application.php:316
4 0.1260 4090072 Zend\EventManager\EventManager->triggerListeners( ) ..\EventManager.php:207
5 0.1270 4091280 call_user_func ( ) ..\EventManager.php:468
6 0.1270 4091568 Zend\Mvc\DispatchListener->onDispatch( ) ..\EventManager.php:468
7 0.1270 4091752 Zend\Mvc\Controller\ControllerManager->get( ) ..\DispatchListener.php:97
8 0.1270 4091936 Zend\ServiceManager\AbstractPluginManager->get( ) ..\ControllerManager.php:137
9 0.1270 4091904 Zend\ServiceManager\ServiceManager->get( ) ..\AbstractPluginManager.php:103
10 0.1270 4092584 Zend\ServiceManager\ServiceManager->create( ) ..\ServiceManager.php:504
11 0.1270 4092728 Zend\ServiceManager\ServiceManager->doCreate( ) ..\ServiceManager.php:572
12 0.1270 4092816 Zend\ServiceManager\AbstractPluginManager->createFromInvokable( ) ..\ServiceManager.php:616
module.config.php
return array(
'router' => array(
'routes' => array(
'wall' => array(
'type' => 'Zend\Mvc\Router\Http\Segment',
'options' => array(
'route' => '/:username',
'constraints' => array(
'username' => '\w+'
),
'defaults' => array(
'controller' => 'Wall\Controller\Index',
'action' => 'index',
),
),
),
),
),
'controllers' => array(
'invokables' => array(
'Wall\Controller\Index' => 'Wall\Controller\IndexController',
),
),
'view_manager' => array(
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
);
module.php
namespace Wall;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module
{
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' , __NAMESPACE__
),
),
);
}
}
IndexController.php
namespace Wall\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\Stdlib\Hydrator\ClassMethods;
use Users\Entity\User;
use Api\Client\ApiClient as ApiClient;
class IndexController extends AbstractActionController
{
public function indexAction()
{
$viewData = array();
$username = $this->params()->fromRoute('username');
$this->layout()->username = $username;
$response = ApiClient::getWall($username);
if ($response !== FALSE) {
$hydrator = new ClassMethods();
$user = $hydrator->hydrate($response, new User());
} else {
$this->getResponse()->setStatusCode(404);
return;
}
$viewData['profileData'] = $user;
return $viewData;
}
}
The error is highly likely within your autoloading configuration
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' , __NAMESPACE__
// ^-- that should be a DOT .
),
),
);
}

ZF2 Translation

I have two modules - Application and StickyNotes. I need to use translation on all pages.
What I do:
1) In view: <?=$this->translate('Home');?>
2) In Application\Module.php:
public function onBootstrap(MvcEvent $e)
{
$translator = $e->getApplication()->getServiceManager()->get('translator');
$eventManager = $e->getApplication()->getEventManager();
$moduleRouteListener = new ModuleRouteListener();
$moduleRouteListener->attach($eventManager);
$app = $e->getParam('application');
$app->getEventManager()->attach('render', array($this, 'setLayoutTitle'));
$translator->setLocale('ru_RU');
echo $translator->getLocale(); //ru_RU
}
3) In StickyNotes\Module.php:
public function onBootstrap(MvcEvent $e)
{
$translator = $e->getApplication()->getServiceManager()->get('translator');
$translator->setLocale('ru_RU');
echo $translator->getLocale(); //ru_RU
}
4) Application\..\module.config.php:
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
),
'aliases' => array(
'translator' => 'MvcTranslator',
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
5) StickyNotes\..\module.config.php same:
'service_manager' => array(
'factories' => array(
'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
),
),
'aliases' => array(
'translator' => 'MvcTranslator',
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
If i try $translator->getLocale(); output 'ru_RU', but translation don`t work.
Also, if I manually change 'locale' => 'en_US', to 'locale' => 'ru_RU',
translation work fine. Thanks for the answers!
in Application\Module.php
public function onBootstrap(MvcEvent $e) {
$translator = $e->getApplication()->getServiceManager()->get('translator');
$lang = $e->getRequest()->getQuery('lang'); // new language
$session = new Container('base');
if($lang == null && $lang == ''){
if ($session->offsetExists('lang')) {
$lang = $session->offsetGet('lang'); // current language
}else{
$lang = Settings::DEFAULT_LANGUAGE; // default language
}
}
$session->offsetSet('lang', $lang);
$loc = Settings::$locations[$lang];
$translator
->setLocale($loc)
->setFallbackLocale(Settings::DEFAULT_LANGUAGE .'_' . Settings::DEFAULT_LOCATION);
}
and Settings class
class Settings{
const DEFAULT_LOCATION = 'IR';
const DEFAULT_LANGUAGE = 'fa';
public static $locations = array(
'fa'=>'fa_IR',
'sa'=>'sa_SA',//Arabic (sa, sa-SA)
'tr'=>'tr_TR',
'en'=>'en_US'
);
}
put translator config only in Application\module.config.php and be sure you have language folder in Application module and put *.mo and *.po file on that .
in the fact , you don't need to set locale in each module . only put in Application\Module.php
in poedit Catalog->properties->Sources keywords-> check "translate" word exist and it's better that be first.
at the end , <?=$this->translate('Home');?> deprecated . use
<?php echo $this->translate('Home');?>
update 1:
sorry , this code <?=$this->translate('Home');?> not deprecated but PHP manual recommendation is <?php echo $this->translate('Home');?>
http://php.net/manual/en/language.basic-syntax.phpmode.php
This problem is due to the absence of intl extension
So just required these steps:
I had to install PHP Intl extension:
sudo apt-get install php5-intl
Apache Restart:
sudo service apache2 restart
Check what extension compiled:
php -m

Class 'Album\Controller\AlbumController' not found

When i try to start album application an error message appears:
Fatal error: Class 'Album\Controller\AlbumController' not found in
C:\xampp\htdocs\ZendSkeletonApplication\vendor\zendframework\zendframework\library\Zend\ServiceManager\AbstractPluginManager.php
on line 170
This is my module.config.php file code
<?php
return array(
'controllers' => array(
'invokables' => array(
'Album\Controller\Album' => 'Album\Controller\AlbumController',
),
),
// Added to make router
'router' => array(
'routes' => array(
'album' => array(
'type' => 'segment',
'options' => array(
'route' => '/album[/][:action][/:id]',
'constraints' => array(
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
'id' => '[0-9]+'
),
'defaults' => array(
'controller' => 'Album\Controller\Album',
'action' => 'index',
),
),
),
),
),
'view_manager' => array(
'template_path_stack' => array(
'album' => __DIR__ . '/../view',
),
),
);
And this is AlbumController.php file code:
<?php
namespace Album\Controller;
use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
class AlbumController extends AbstractActionController {
protected $albumTable;
public function indexAction() {
return new ViewModel(array(
'album' => $this->getAlbumTable()->fetchAll(),
));
}
public function addAction() {
}
public function editAction() {
}
public function deleteAction() {
}
public function getAlbumTable () {
if (!$this->albumTable) {
$sm = $this->getServiceLocator();
$this->albumTable = $sm->get('Album\Model\AlbumTable');
}
return $this->albumTable;
}
}
i see you are just getting started, so i would refer to this code by Martin Shwalbe and find out if you have any typo. If everything looks good, then you probably have issue in the way you are accessing it.
https://github.com/Hounddog/Album
hope this helps...

Chaining Dependency Injection in ZF2

I am trying to create a simple email templating test in ZF2, I am using Dependency injection in order to create an instance of the PhpRenderer class, with all the dependencies set.
It appears that I may be struggling with chaining the injections as the path 'email' is not present in the AggregateResolver.
inside module.config.php
'di' => array(
'instance' => array(
'Zend\View\Resolver\TemplatePathStack' => array(
'options' => array(
'script_paths' => array(
'email' => __DIR__ . '/../view/application/email',
),
),
),
'Zend\View\Resolver\AggregateResolver' => array(
'attach' => array(
'Zend\View\Resolver\TemplatePathStack',
),
),
'Zend\View\Renderer\PhpRenderer' => array(
'setResolver' => 'Zend\View\Resolver\AggregateResolver',
),
),
),
inside TestController.php
$di = new \Zend\Di\Di;
$renderer = $di->get('Zend\View\Renderer\PhpRenderer');
$content = $renderer->render('email/test', null);
echo($content);
Message:
Zend\View\Renderer\PhpRenderer::render: Unable to render template "email/test"; resolver could not resolve to a file
Any help would be gratefully received.
Since writing the above, I was playing around and removed the TemplatePathStack from the di array and this had no effect at all, So I am not sure it is being used at all by the AggregateResolver, so it may be a chaining issue:
'di' => array(
'instance' => array(
/*'Zend\View\Resolver\TemplatePathStack' => array(
'addPaths' => array(
'paths' => array(
'email' => __DIR__ . '/../view/application/email',
),
),
),*/
'Zend\View\Resolver\AggregateResolver' => array(
'attach' => array(
'Zend\View\Resolver\TemplatePathStack',
),
),
'Zend\View\Renderer\PhpRenderer' => array(
'setResolver' => 'Zend\View\Resolver\AggregateResolver',
),
),
),
Aborgrove
In the end I solved it by moving the di array out of the module.conf.php and recreating it in the Module getServiceConf() method. (Although I am not sure this is the best place to put it)
public function getServiceConfig()
{
return array(
'factories' => array(
// using the Session Manger to create one instance of the follwing models
......... more code here ............
'EmailTemplatePathStack' => function($sm) {
$template_path_stack = new \Zend\View\Resolver\TemplatePathStack();
$paths = array('emailfolder' => __DIR__ . '/view/application/email');
$template_path_stack->addPaths($paths);
return $template_path_stack;
},
'EmailAggregateResolver' => function($sm) {
$resolver = new \Zend\View\Resolver\AggregateResolver();
$resolver->attach($sm->get('EmailTemplatePathStack'));
var_dump($resolver);
return $resolver;
},
'EmailPhpRenderer' => function($sm) {
$php_renderer = new \Zend\View\Renderer\PhpRenderer();
$php_renderer->setResolver($sm->get('EmailAggregateResolver'));
return $php_renderer;
},
),
);
}
Then changing the controller to:
$sm = \Application\Model\ServiceLocatorFactory::getInstance();
$renderer = $sm->get('EmailPhpRenderer');
$content = $renderer->render('test.phtml', null);
echo($content);

ServiceNotFoundException in ZendFramework 2, example from Rob Allen

for the past few weeks I have been following ZF2 especially Rob Allen's 'Album' example , I have created the example DB-'zf2tutorial' and example table-'album', which works fine fetching all the items when I use php-mysql, so problems with the data in the DB.
My local.php looks like this
config.autoload/local.php:
return array(
'db' => array
(
'driver' => "Pdo",
'dsn' => "mysql:dbname=zf2tutorial;hostname=localhost",
'username' => "user", //here I added my valid username
'password' => "password", //here I added my valid password
'driver_options' => array
(
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES 'UTF8'"
),
),
);
Module.php
**module/Album/Model.php
<?php
namespace Album;
use Album\Model\AlbumTable;
class Module
{
public function getAutoloaderConfig()
{
return array(
'Zend\Loader\ClassMapAutoloader' => array(
__DIR__ . '/autoload_classmap.php',
),
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig()
{
return include __DIR__ . '/config/module.config.php';
}
public function getServiceConfiguration()
{
return array(
'factories' => array(
'album-table' => function($sm) //also tried this 'Album\Model\AlbumTable' => function($sm)
{
$dbAdapter = $sm->get('db-adapter');//also tried this $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
$table = new AlbumTable($dbAdapter);
return $table;
},
),
);
}
}
I just wanted to check whether the zf2turorial/album works or not it does throw this error which is similar to this post here in stackoverlow.
The error which it is throwing is:
Additional information:
Zend\ServiceManager\Exception\ServiceNotFoundException
File:
..\vendor\zendframework\zendframework\library\Zend\ServiceManager\ServiceManager.php:392
Message:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Album\Model\AlbumTable
I have followed ZF2 Beta 5 tutorial as well, but still encountering this problem. In case if anyone has a solution, please do share with us.
Thanks
seems like somebody has forgotten to update the newest changes in zf2.
the solution:
the file module/Album/Module.php has to contain this content:
<?php
namespace Album;
use Album\Model\AlbumTable;
use Zend\ModuleManager\Feature\ServiceProviderInterface;
class Module implements ServiceProviderInterface
then you have to rename
public function getServiceConfig()
to
public function getServiceConfiguration()
public function getServiceConfiguration() is not the correct function name
rename getServiceConfiguration() to getServiceConfig()
although it is not mandatory you should declare the class Module as
class Module implements ServiceProviderInterface
I am not sure but try to put the code into
config.autoload/global.php: like this way
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=kd_tutorial;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
I have encoutered the same problem when try to implement code follow zend tutorial. The main reason is order-folder
module
ModuleX
config
src
ModuleX //may be you forget this one
Controller
Factory
Model
...
view
Module.php
in Module.php, getConfig(), getAutoloaderConfig() is enough to run
class Module implements AutoloaderProviderInterface, ConfigProviderInterface{
public function getAutoloaderConfig(){
return array(
'Zend\Loader\StandardAutoloader' => array(
'namespaces' => array(
__NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
),
),
);
}
public function getConfig(){
return include __DIR__ . '/config/module.config.php';
}
Modify config/autoload/global.php with following code:
return array(
'db' => array(
'driver' => 'Pdo',
'dsn' => 'mysql:dbname=YourDBName;host=localhost',
'driver_options' => array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
),
),
'service_manager' => array(
'factories' => array(
'Zend\Db\Adapter\Adapter'
=> 'Zend\Db\Adapter\AdapterServiceFactory',
),
),
);
and You should put your database credentials in config/autoload/local.php so that they are not in the git repository (as local.php is ignored):
return array(
'db' => array(
'username' => 'YourDBUsername',
'password' => 'YourDBPassword',
),
);
If you want more details refer link1 or link2
Just got the same issue.
Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Cache\Model\UniversityStorage
In my case the problem was, that PHPUnit could not find the key Cache\Model\UniversityStorage in the service manager (registry) because it's being added in the Module class of the Cache module and the Cache module was missing in the PHPUnit config file and was also not being loaded:
/module/Application/test/phpunit.config.php
<?php
return array(
'modules' => array(
'Application',
'Cache', // <- was missing
),
'module_listener_options' => array(
'config_glob_paths' => array(
'../../../config/autoload/{,*.}{global,local}.php',
),
'module_paths' => array(
'module',
'vendor',
),
),
);
I've added the Cache module to the module list. Now it works.
The problem is that within config/autoload/global.php the service is named "Zend\Db\Adapter\Adapter" while within module/Album/Module.php it was searching for "Zend\Db\Adapter" (missing additional \Adapter).
Adding missing "\Adapter" within module/Album/Module.php like this fixed it for me.
'AlbumTableGateway' => function($sm) {
$dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
In module/Album/src/Album/Model/Album.php, use instead:
array('name' => 'striptags'),
array('name' => 'stringtrim'),
See the above namespaces created by Zend at vendor/zendframework/zendframework/library/Zend/Filter/FilterPluginManager.php
If you are getting similar error for different modules and the code seems jus right then ADD an entry in composer.json
"Album\": "module/Album/src/"
in autoload and autoload-dev section like this where Album is the name of your Module
"autoload": {
"psr-4": {
"Application\\": "module/Application/src/",
"Album\\": "module/Album/src/"
}
},
"autoload-dev": {
"psr-4": {
"ApplicationTest\\": "module/Application/test/",
"Album\\": "module/Album/src/"
}
},
after this run "composer update" and reload the page. check if error is gone.

Resources