unserialize cache zend doctrine2 - zend-framework

Hi can you help me please! I want to use zend cache file since im in shared hosting.
So the problem is i cant retrieve cached doctrine file result. data has serialized coz it 's object. $cache->load($id) return as array i can't unserialize back.
Please i will glad if you could help me or suggest something. Here my code.
$request = $this->getRequest();
$slug = $request->getParam('slug');
$front = Zend_Controller_Front::getInstance();
$bootstrap= $front->getParam('bootstrap');
$cache = $bootstrap->getResource('cachemanager')->getCache('content');
$cacheId = md5('news_' . $slug);
if ( !($news = **unserialize($cache->load($cacheId))**) ) {
$news = $this->_em->getRepository('Custom\Entity\News')
->findOneBySlug($slug);
$cache->save($news, $cacheId);
var_dump('if u see me that mean not from cached');
}
$page = new Zend_Navigation_Page_Mvc(array(
'label' => $news[0]->getTitle(),
'route' => 'news-view',
'module' => 'news',
'controller' => 'index',
'action' => 'view',
'params' => array(
'slug' => $news[0]->getAlias())
)
);
$page->setActive(false);
$this->_helper->navigation->getContainer()
->findOneBy('uri', '/category/' . $news[0]->getCategory()->getSlug())
->addPage($page);
$this->view->ogpa = new OpenGraphProtocolArticle();
$this->view->news = $news;
$this->view->headTitle($news[0]->getTitle());

Do not save any Doctrine2 models in Zend_Cache see: https://ssmusoke.com/2012/03/25/doctrine2-day-3-proxies-associations-relationships/
This is because in the background Doctrine2 uses proxy classes which cannot be unserialized by the Zend auto loader, which will cause you a great deal of grief ...
If you are to cache anything, cache the output not the models.

Related

Zend Controller Router : Define variables to point to a different action in one controller

I'm just new with Zend and I have a little trouble with Zend Routers. I've searched about it, but nothing found...
I want to be able to define a router for each defined variable at uri level to point to a different action in one controller.
I'm working with lang and modules so I defined at bootstrap application the next initRoutes function:
protected function _initRoutes()
{
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
$defaultRoute = new Zend_Controller_Router_Route(
':lang/:module/:controller/:action',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'index',
'action' => 'index'
),
array(
'lang' => '^(en|es)$',
'module' => '^(default|admin)$'
)
);
$router->addRoute('defaultRoute', $defaultRoute);
return $router;
}
I want to be able to access forum sections and forum topics by their defined action.
Something like :
mydomain/forum -> forum/index
mydomain/forum/section -> forum/sectionAction
mydomain/forum/section/topic -> forum/topicAction
and also with the lang and module defined at uri level like :
mydomain/lang/module/forum
mydomain/lang/module/forum/section
mydomain/lang/module/forum/section/topic
So I have this :
class ForumController extends Zend_Controller_Action
{
public function indexAction()
{
}
public function sectionAction()
{
}
public function topicAction()
{
}
Then I created the next routes inside the Default_Bootstrap :
$forumRoutes = new Zend_Controller_Router_Route(
':lang/:module/forum',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'index'
)
);
$sectionRoutes = new Zend_Controller_Router_Route(
':lang/:module/forum/:section',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'section',
'section' => ''
)
);
$topic = new Zend_Controller_Router_Route(
':lang/:module/forum/:section/:topic',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'topic',
'section' => '',
'topic' => ''
)
);
$router->addRoute('forumTopics', $topic);
$router->addRoute('forumSections', $section);
$router->addRoute('forum', $forumRoutes);
Now, this only works if I define the lang and module at uri level, but doesn't work if I defined like => mydomain/forum/section | section/topic. This also brings me another problem with my navigation->menu. If I define "forum" as a static variable at router definition, when I hover over at any label defined at navigatoin.xml, the uri level have the same value for every one of them.
I've tried to make a chain like this:
$forumRoutes = new Zend_Controller_Router_Route(
':lang/:module/forum',
array(
'lang' => 'es',
'module' => 'default',
'controller' => 'forum',
'action' => 'index'
)
);
$section = new Zend_Controller_Router_Route(
':section',
array(
'action' => 'section',
'section' => ''
)
)
$topic = new Zend_Controller_Router_Route(
':topic',
array(
'action' => 'topic',
'topic' => ''
)
)
$chainedRoute = new Zend_Controller_Router_Route_Chain();
$chainedRoute->chain($topic)
->chain($section)
->chain($forumRoutes);
$router->addRoute($chainedRoute);
But this doesn't work as I expected.
Any help would be appreciated, thanks.
You are new to Zend. You said it. So here are some explanations:
Ideally the URL on Zend application is:
example.com/controller/action/param-name/:param-value
So in which case, if there is an action called Edit under UsersController, it will be:
example.com/users/edit
if action is add, it will be :
example.com/users/add
when you specify first parameter as a variable, it will collide with controller requests. Example: if you say controller is User but first parameter accepts a value and puts it in emplyees then a request as example.com/employees and example.com/user will both point towards employees controller even if the usercontroller exists! which again is a theory!
What you might want to do is, leave the routes to only accept dynamic values rather routing! You do not want users to route your application but, route user to different sections of the application.
About language then you need to use Zend_Locale which will check for HTML language that is
<html lang="nl"> or <html lang = "en">
Hope things are clear! :)
Here's a quick example which should help you work with routes like that in ZF.
If you are using a default project structure like the one you get when starting a new project using Zend Tool go into the Application folder.
In your Bootstrap.php set up something like this:
protected function _initRouteBind() {
// get the front controller and get the router
$front = Zend_Controller_Front::getInstance();
$router = $front->getRouter();
// add each custom route like this giving them a descriptive name
$router->addRoute(
'addTheDescriptiveRouteNameHere',
new Zend_Controller_Router_Route(
'/:controller/:id/:action/:somevar',
array(
'module' => 'default',
'controller' => ':controller',
'action' => ':action',
'id' => ':id',
'somevar' => ':somevar'
)
)
);
}
My example above is just to illustrate how you would use a route where the controller, the action and a couple of parameters are set in the url.
The controller and action should be resolved without any additional work however to get the 'id' or 'somevar' value you can do this in your controller:
public function yourAction()
{
// How you get the parameters to pass in to a function
$id = $this->getRequest()->getParam('id');
$somevar = $this->getRequest()->getParam('somevar');
// Using the parameters
$dataYouWant = $this->yourAmazingMethod($id);
$somethingElse = $this->yourOtherAmazingMethod($somevar);
// Assign results to the view
$this->view->data = $dataYouWant;
$this->view->something = $somethingElse;
}
So while you will want to make sure your methods handle the parameters being passed in with care (after all it is user supplied info) this is the principle behind making use of the route parameter binding. You can of course do things like '/site' as the route and have it direct to a CMS module or controller, then another for '/site/:id' where 'id' is a page identifier.
Also just to say a nice alternative to:
$id = $this->getRequest()->getParam('id');
$somevar = $this->getRequest()->getParam('somevar');
which wasn't that nice itself anyway since it was assuming a parameter was going to be passed, using shorthand conditional statement in conjunction with action helpers is:
$id = ($this->_hasParam('id')) ? $this->_getParam('id') : null;
$somevar = ($this->_hasParam('somevar')) ? $this->_getParam('somevar') : null;
If you are not familiar with this, the
($this->_hasParam('id'))
is the conditional test which if true assigns the value of whatever is on the left of the ':' and which if false assigns the value of whatever is on the right of the ':'.
So if true the value assigned would be
$this->_getParam('id')
and null if false.
Does that help? :-D

Zend Doctrine Session SaveHandler. How make it work?

I am trying to understand how to set up a Session Save Handler (with Zend/Doctrine) using a database table but I am a bit confused about how it all should work.
I found this proposal that I think it suits my needs as I am also working with Doctrine.
All is set up: the proper class, the database table and Doctrine Model. What I don't get is this part:
$config = array(
'tableName' => 'Session',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime',
'modifiedColumn' => 'modified',
'primaryKeyColumn' => 'id',
);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_Doctrine($config));
Zend_Session::start();
I am confused here. Where should this part go? Can anyone please help? Or maybe point me to some useful tutorial to do this?
This should go in your main bootstrap class (application/Bootstrap.php). So I'd add something like this:
protected function _initDoctrineSession()
{
$config = array(
'tableName' => 'Session',
'dataColumn' => 'data',
'lifetimeColumn' => 'lifetime',
'modifiedColumn' => 'modified',
'primaryKeyColumn' => 'id',
);
Zend_Session::setSaveHandler(new Zend_Session_SaveHandler_Doctrine($config));
Zend_Session::start();
}

How mvc works in Zend framework

Thanks for previous replies..
I am trying to print Hello_world using zend framework. I wrote php file in model folder and return string value as a "Hello_world". In controller i access the value of PHP like this
$value = new TextReturner();
$this->view->setValue = $value->hello_world(); . i dont know how to access the value from controller to the view php file. I am new to zend framework. I already go through the outline structure of zend framework, i dont know how to access through codings. If anyone have idea of how to print hello_world through MVC pls guide me.
You are trying to use class $value = new TextReturner(); but your controller doesn't see that class.
Set this in your Bootstrap file that will help:
protected function _initAutoLoad() {
// Add autoloader empty namespace
$autoLoader = Zend_Loader_Autoloader::getInstance();
$resourceLoader = new Zend_Loader_Autoloader_Resource(
array(
'basePath' => APPLICATION_PATH,
'namespace' => '',
'resourceTypes' => array(
'model' => array(
'path' => 'models/',
'namespace' => 'Model_'
),
),
)
);
return $resourceLoader;
}
This will be autoload all of your model class.
in view you can access your variable like this:
<?php echo $this->setValue;?>

Recovering a parameter over the bootstrap Zend Framework

I am developing an application in Zend framework. In my bootstrap I have a method named _initRoutes:
public function _initRoutes(){
$router = $this->_front->getRouter();
$default = new Zend_Controller_Router_Route(':language/:controller/:action/*',
array(
'language' => Model_Db_Option::read('site_default_language'),
'module' => 'public',
'controller' => 'index',
'action' => 'index'
),
array(
'language' => '^[a-z]{2}$*'
)
);
}
Hoy can I recover the language value in the _initRoutes??? How can I get this value in the next function _initLocale
PS. I know that I can recover it as parameter from request but I want to recover it in the bootstrap.
i used this
$params=#$default->match($this->_front->getRequest()->getRequestUri());
$lang=$params['language'];
try
$language = Zend_Controller_Front::getInstance()->getRequest()->getParam('language');
something like this, can't test from this comp

How to define the use of utf-8 in Doctrine 2 in Zend Framework application.ini, when using Bisna

The following ZendCasts cast, shows a way to use doctrine 2 in a zend framework environment.
Using this configuration, how can I make the connection use a utf-8 charset so the magic of "SET NAMES 'utf8'" will happen ?
What I'm really searching for is a way to configure it using the application.ini file.
If that's not possible using this configuration, how can this be done by code ? an _initDoctrine method in the Bootstratp file ?
Thank you.
UPDATE
It appears there's a post connect event which handles this, but I don't see how can I set it up via application.ini (if possible at all).
If not, can I set it up via a bootstrap method ? Will the bootstrap method run before any other doctrine connection code run, when relying on the Bisna library ?
If you are not using Bisna, you could simply do something like the following:
Pass the config stuff directly to EntityManager's connection options
(although driverOptions is not documented)
// $options is a simple array to hold your data
$connectionOptions = array(
'driver' => $options['conn']['driv'],
'user' => $options['conn']['user'],
'password' => $options['conn']['pass'],
'dbname' => $options['conn']['dbname'],
'host' => $options['conn']['host'],
'charset' => 'utf8',
'driverOptions' => array(
1002 => 'SET NAMES utf8'
)
);
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
I'm using the following custom bootstrap resource to initialize doctrine therefore $options is in application.ini and is accessible there by $this->getOptions();
// \library\My\Application\Resource\Doctrine.php
class My_Application_Resource_Doctrine extends Zend_Application_Resource_ResourceAbstract
{
public function init()
{
$options = $this->getOptions();
$config = new \Doctrine\ORM\Configuration();
//doctrine autoloader, config and other initializations
...
$connectionOptions = array(
.... //see above
);
$em = \Doctrine\ORM\EntityManager::create($connectionOptions, $config);
$registry = Zend_Registry::getInstance();
$registry->em = $em;
return $em;
}
}
It will bootstrap automatically if you put in application.ini
resources.doctrine.conn.host = '127.0.0.1'
resources.doctrine.conn.user = '...'
resources.doctrine.conn.pass = '...'
....
works fine for me
resources.doctrine.dbal.connections.default.parameters.driverOptions.1002 = "SET NAMES 'UTF8'"
1002 is the integer value of PDO::MYSQL_ATTR_INIT_COMMAND:
Command to execute when connecting to the MySQL server. Will
automatically be re-executed when reconnecting.
Note, this constant can only be used in the driver_options array when constructing a new
database handle.
this worked for me. config/autoload/doctrine.local.php
<?php
return array(
'doctrine' => array(
'connection' => array(
'orm_default' => array(
'driverClass' => 'Doctrine\DBAL\Driver\PDOMySql\Driver',
'params' => array(
'host' => 'localhost',
'port' => '3306',
'user' => '...',
'password' => '...',
'dbname' => '...',
'driverOptions' => array(
\PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8'
)
),
)
)
)
);
It is possible to add it via application.ini, provided you use ZendX_Doctrine2 (at https://github.com/mridgway/ZendX_Doctrine2) with MySQL.
Then here's the line you need in application.ini:
resources.entitymanagerfactory.connectionOptions.driverOptions.1002 = "SET NAMES utf8"
(1002 == PDO::MYSQL_ATTR_INIT_COMMAND)
Don't forget to correctly set
default-character-set=utf8
in your my.cnf
Since this is for Doctrine 2, and ZendCasts is using Bisna, I believe you can just add this to your configuration.ini file
resources.doctrine.dbal.connections.default.parameters.driverOptions.charset = "utf8"
I'm not exactly sure how to test if it is sticking or not but let us know.
You could set the default table charset like that to utf8:
// Create new Doctrine Manager instance
$doctrineManager = Doctrine_Manager::getInstance();
// Set charset to UTF8
$doctrineManager->setAttribute(
Doctrine_Core::ATTR_DEFAULT_TABLE_CHARSET,
'utf8'
);
Quote:
an _initDoctrine method in the Bootstratp file ?
Yes.
For LoSo library and Doctrine 2 and MySQL add
resources.doctrine2.connection.driverOptions.1002 = "SET NAMES 'UTF8'"
to your application.ini
I have this in my bootstrap:
protected function _initDoctrineLibrary()
{
require_once('Doctrine/Doctrine.php');
$this->getApplication()->getAutoloader()->pushAutoloader(array('Doctrine', 'autoload'),'Doctrine');
$manager = Doctrine_Manager::getInstance();
$manager->setAttribute(
Doctrine::ATTR_MODEL_LOADING,
Doctrine::MODEL_LOADING_CONSERVATIVE
);
$config = $this->getOption('doctrine');
$conn = Doctrine_Manager::connection($config['dsn'],'doctrine');
$conn->setAttribute(Doctrine::ATTR_USE_NATIVE_ENUM, true);
return $conn;
}
where in the application.ini you see
doctrine.dsn = "mysql://user:password#host/databasename"
I think you can do something similar