How to save XMLobject in memcahe in Zend Framwork2 - php

Below is my part of code(in ZF2) where I am trying to save an XML object into Memcache, But I am unable to figure it out why its not setting up Complex obejct into Memcache, Any lead ?
$serviceManager = $event->getApplication()->getServiceManager();
$xmlAclConfigCache = $serviceManager->get('memcache')->getItem('xmlConfig');
if (empty($xmlAclConfigCache)) {
echo 'fresh ACL XML';
$xmlAclConfigCache = simplexml_load_file(__DIR__.'/config/acl.xml');
$serviceManager->get('memcache')->setItem('xmlConfig', $xmlAclConfigCache);
var_dump($xmlAclConfigCache);
} else {
echo 'OLD ACL XML';
}
Memcache config in cache.local.php
<?php
return array(
'caches' => array(
'memcache' => array( //can be called directly via SM in the name of 'memcached'
'adapter' => array(
'name' =>'memcache',
'ttl' => 7200,
'options' => array(
'servers' => array(
array(
'127.0.0.1',11211
)
),
'namespace' => 'MYMEMCACHEDNAMESPACE',
)
),
'plugins' => array(
'exception_handler' => array(
'throw_exceptions' => false
),
),
),
),
);

Related

Elastica add documents overrides existing ones

When i try to add new documents to an index type , i loose existing documents which are overwritten by the new added ones . The problem can be related to the id of each added document ??
Here is the code :
$elasticaClient = new \Elastica\Client(array(
'host' => $this->container->getParameter('elastic_host'),
'port' => $this->container->getParameter('elastic_port')
));
$elasticaIndex = $elasticaClient->getIndex('app');
$elasticaIndex->create(
array(
'number_of_shards' => 4,
'number_of_replicas' => 1,
'analysis' => array(
'analyzer' => array(
'indexAnalyzer' => array(
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => array('lowercase', 'mySnowball')
),
'searchAnalyzer' => array(
'type' => 'custom',
'tokenizer' => 'standard',
'filter' => array('standard', 'lowercase', 'mySnowball')
)
),
'filter' => array(
'mySnowball' => array(
'type' => 'snowball',
'language' => 'German'
)
)
)
),
true
);
$elasticaType = $elasticaIndex->getType('type');
$mapping = new \Elastica\Type\Mapping();
$mapping->setType($elasticaType);
$mapping->setParam('index_analyzer', 'indexAnalyzer');
$mapping->setParam('search_analyzer', 'searchAnalyzer');
$mapping->setProperties(array(
'id' => array('type' => 'string'),
'title' => array('type' => 'string'),
'duration' => array('type' => 'string'),
'start' => array('type' => 'string'),
'end' => array('type' => 'string'),
));
// Send mapping to type
$mapping->send();
$documents = array();
foreach($medias as $media) {
$id = uniqid() ;
$documents[] = new \Elastica\Document(
$id,
array(
'id' => $id,
'title' => $media['title'],
'duration' => $media['duration'],
'start' => $media['start'],
'end' => $media['end'],
)
);
}
$elasticaType->addDocuments($documents);
$elasticaType->getIndex()->refresh();
Please i need your help . Thank you
PHP does not recommend using uniqid for this use case. Since you are wanting a random, safe id, let Elasticsearch do it for you. The Elastica Document construct method notes that the id field is optional. So don't pass it and let Elasticsearch issue the id.
Several things
$elasticaIndex->create (....) you only have to enter it once. Index is unique after creating the index that you can comment or generate a different index and other things. I leave an example that works.
class PersistencyElastic
{
private $conection;
public function __construct()
{
$this->conection = new \Elastica\Client(['host' => '127.0.0.1', 'port' => 9200]);
}
public function save($ msg)
{
// $ msg is an array with whatever you want inside
$index = $this->conection->getIndex('googlephotos');
// This is the index I created, it's called googlephotos
// $index->create(array (), true);
$type = $index->getType('googlephotos');
$type->addDocument(new Document (uniqid ('id _', false), $msg, $type, $index));
$index->refresh();
}
}

Cakephp Form is not getting submiited but giving Notice (8): Array to string Coversion, many other Warnings (2)

I am having trouble submitting/saving data to the CakePHP Model. I constructed the form as usual as I always do, but this time I am getting notices and warning an also data is not getting saved. Here is the form I have constructed and method in Controller:
educationaldetails.ctp
<?php
if (empty($Education)):
echo $this->Form->create('Candidate', array('class' => 'dynamic_field_form'));
echo $this->Form->input('CandidatesEducation.0.candidate_id', array(
'type' => 'hidden',
'value' => $userId
));
echo $this->Form->input('CandidatesEducation.0.grade_level', array(
'options' => array(
'Basic' => 'Basic',
'Masters' => 'Masters',
'Doctorate' => 'Doctorate',
'Certificate' => 'Certificate'
)
));
echo $this->Form->input('CandidatesEducation.0.course');
echo $this->Form->input('CandidatesEducation.0.specialization');
echo $this->Form->input('CandidatesEducation.0.university');
echo $this->Form->input('CandidatesEducation.0.year_started', array(
'type' => 'year'
));
echo $this->Form->input('CandidatesEducation.0.year_completed', array(
'type' => 'year'
));
echo $this->Form->input('CandidatesEducation.0.type', array(
'options' => array(
'Full' => 'Full',
'Part-Time' => 'Part-Time',
'Correspondence' => 'Correspondence'
)));
echo $this->Form->input('CandidatesEducation.0.created_on', array(
'type' => 'hidden',
'value' => date('Y-m-d H:i:s')
));
echo $this->Form->input('CandidatesEducation.0.created_ip', array(
'type' => 'hidden',
'value' => $clientIp
));
echo $this->Form->button('Submit', array('type' => 'submit', 'class' => 'submit_button'));
echo $this->Form->end();
endif;
CandidatesController.php
public function educationaldetails() {
$this->layout = 'front_common';
$this->loadModel('CandidatesEducation');
$Education = $this->CandidatesEducation->find('first', array(
'conditions' => array(
'candidate_id = ' => $this->Auth->user('id')
)
));
$this->set('Education', $Education);
// Checking if in case the Candidates Education is available then polpulate the form
if (!empty($Education)):
// If Form is empty then populating the form with respective data.
if (empty($this->request->data)):
$this->request->data = $Education;
endif;
endif;
if ($this->request->is(array('post', 'put')) && !empty($this->request->data)):
$this->Candidate->id = $this->Auth->user('id');
if ($this->Candidate->saveAssociated($this->request->data)):
$this->Session->setFlash('You educational details has been successfully updated', array(
'class' => 'success'
));
return $this->redirect(array(
'controller' => 'candidates',
'action' => 'jbseeker_myprofile',
$this->Auth->user('id')
));
else:
$this->Session->setFlash('You personal details has not been '
. 'updated successfully, please try again later!!', array(
'class' => 'failure'
));
endif;
endif;
}
Here is the screenshot of errors I am getting, Not able to figure out what is happening while other forms are working correctly. looks like something something wrong with view?
This error is coming out because you are not passing the proper arguments to the session->setFlash() method, you are doing like this:
$this->Session->setFlash('You personal details has not been updated successfully, please try again later!!', array(
'class' => 'failure'
));
In docs it is mentioned like:
$this->Session->setFlash('You personal details has not been updated successfully, please try again later!!',
'default', array(
'class' => 'failure'
));
Hi so if i understand :
array(
'CandidatesEducation' => array(
(int) 0 => array(
'candidate_id' => '5',
'grade_level' => 'Basic',
'course' => 'Masters of Computer Application',
'specialization' => '',
'university' => 'Mumbai University',
'year_started' => array(
'year' => '2011'
),
'year_completed' => array(
'year' => '2014'
),
'type' => 'Full',
'created_on' => '2014-11-27 15:44:36',
'created_ip' => '127.0.0.1'
)
)
),
Is your data , and you just need to save this in your candidates_educations table , so in this case i would do :
$this->Candidate->CandidatesEducation->save($this->request->data);
and your $data had to look :
array(
'CandidatesEducation' => array(
'candidate_id' => '5',
'grade_level' => 'Basic',
'course' => 'Masters of Computer Application',
'specialization' => '',
'university' => 'Mumbai University',
'year_started' => array(
'year' => '2011'
),
'year_completed' => array(
'year' => '2014'
),
'type' => 'Full',
'created_on' => '2014-11-27 15:44:36',
'created_ip' => '127.0.0.1'
)
);
the saveAssociated is used when you create your Model AND Model associated , not only your Associated model.
And : i m not sure for year_started and year completed rm of data, it depends of your table schema ; what's the type of year_completed and year_started ?

Grant ACL permission by URLs in Zend Framework 2

I follow this tutorial: http://ivangospodinow.com/zend-framework-2-acl-setup-in-5-minutes-tutorial/
But, I want to grant permission by custom URLs, so I had some changes in my code.
In module.acl.roles.php
return array(
'guest'=> array(
'/home.html',
'/login.html',
'/register.html'
),
'admin'=> array(
'/user/add.html',
'/user/edit.html',
'/user/list.html',
),
);
In module.config.php
return array(
'router' => array(
'routes' => array(
'/home.html' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
'/user/add.html' => array(
'type' => 'Zend\Mvc\Router\Http\Regex',
'options' => array(
'regex' => '/user/add.html',
'defaults' => array(
'controller' => 'Application\Controller\User',
'action' => 'add',
'format' => 'html',
),
'spec' => '/user/add.%format%',
),
),
...
),
),
);
But I received this error: Route with name "" not found. Please give me some advices and solutions to grant permission by URLs
Thank you!
I really really recommend the BjyAuthorize module (https://packagist.org/packages/bjyoungblood/bjy-authorize).
But if you really want to do this by yourselft you need to add a listener to the \Zend\Mvc\MvcEvent::EVENT_ROUTE.
You can attach your listener with
$events->attach(MvcEvent::EVENT_ROUTE, array($this, 'myOnRoute'), -1000);
and in your myOnRoute method you can handle the route
public function myOnRoute(MvcEvent $event) {
$match = $event->getRouteMatch();
$routeName = $match->getMatchedRouteName();
// do stuff here (compare to config or whatever)
}

Multiple loggers

I'd like to create multiple loggers where different areas of my app will log to different files. For example, all the classes associated with getting the users data would log to a user.log, all functionality of making purchases going to a purchase.log. I am using the configuration array method for setting up the logger & appenders. In my index.php:
require_once('log4php/Logger.php');
require_once('classB.php');
require_once('classA.php');
Logger::configure(array(
'rootLogger' => array('appenders' => array('default')),
'classALogger' => array('appenders' => array('classAAppender')),
'appenders' => array(
'default' => array(
'class' => 'LoggerAppenderEcho',
'layout' => array(
'class' => 'LoggerLayoutSimple'
)
),'classAAppender' => array(
'class' => 'LoggerAppenderFile',
'additivity' => false,
'layout' => array(
'class' => 'LoggerLayoutSimple'
),
'params' => array(
'file' => 'log/classA.log',
'append' => true
)
)
),
));
$logger = Logger::getLogger("main");
$logger->info('message from index' . '<br>');
$classA = new ClassA();
$classA->test();
Class A is as follows:
class ClassA
{
public function test()
{
$logger = Logger::getLogger("classALogger");
$logger->error('from ClassA');
}
}
I am able to log to the default or root logger but am not able to log to, in this example, classALogger. Any suggestions?

Combining HeadScript javascript with widmogrod/zf2-assetic-module and js in multiple modules

Running into a bit of a hurdle, and I can't find any supporting documentation. My use case is fairly simple. The Application module has javascript that should go into the head, and one of my other modules, Foo also has script that should go into the head. I assumed that this Assetic module could solve that. Here's what I inferred:
Application Config
/**
* Assetic
*/
'assetic_configuration' => array(
'buildOnRequest' => true,
'cacheEnabled' => false,
'webPath' => realpath('public/assets'),
'basePath' => 'assets',
'default' => array(
'assets' => array(
'#base_css',
'#head_js',
),
'options' => array(
'mixin' => true,
),
),
'modules' => array(
'application' => array(
# module root path for yout css and js files
'root_path' => __DIR__ . '/../assets',
# collection of assets
'collections' => array(
'base_css' => array(
'assets' => array(
'css/*.css',
),
'filters' => array(),
'options' => array(),
),
'head_js' => array(
'assets' => array(
'js/*.js',
),
'filters' => array(),
),
'base_images' => array(
'assets'=> array(
'images/*.png',
),
'options' => array(
'move_raw' => true,
)
),
),
),
),
),
and then in my Foo module...
Foo Module config
/**
* Assetic
*/
'assetic_configuration' => array(
'default' => array(
'assets' => array(
'#base_css',
'#head_js',
),
'options' => array(
'mixin' => true,
),
),
'modules' => array(
'foo' => array(
# module root path for yout css and js files
'root_path' => __DIR__ . '/../assets',
# collection of assets
'collections' => array(
'base_css' => array(
'assets' => array(
'css/*.css'
),
'filters' => array(),
'options' => array(),
),
'head_js' => array(
'assets' => array(
'js/*.js' // relative to 'root_path'
),
'filters' => array(),
'options' => array(),
),
'base_images' => array(
'assets'=> array(
'images/*.png'
),
'options' => array(
'move_raw' => true,
)
),
),
),
),
),
With this config, unfortunately, only the Foo module's javascript makes its way into head_js.js. I'm feeling like that meme with Milton in it, going "I was told there would be asset combining!" :)
Any help you could offer, is appreciated.
Thanks!
Ok - I've figured it out. Hopefully this helps someone else one day. The configuration keys I noted above weren't inaccurate -- but -- they weren't crafted properly when a secret undocumented feature is considered; had to crack the source open to learn that including the word 'head' in an asset bundle actually autoloads it in the head. It's a nice feature in the end, but really a head scratcher when you're not aware of it.

Categories