How I can store the array in Redis and retrive the array items using redis in PHP - phpredis

I have following PHP array and I want to store it in Redis. Also I want to retrieve all the array items whenever needed to perform the operation. How can I achieve this. Please help.
Following is my PHP/redis code:
$data['xxx'] = array(
'created' => date("Y-m-d H:i:s"),
'tracking_id' => 'abCd',
'affiliate_id' => 100,
);

Serialize it to store and unserialize after retrieve. Redis simply store a document.
In order to keep it agnostic, encode it in json:
json_encode($yourArray);
To retrieve:
$yourData = json_decode($redisStoradeValue);

Related

How to retrieve data from model using findByType in cakephp?

I am trying to find records from CallForwardingCondition model using following line of code:
$this->loadModel('CallForwardingCondition');
$this->set('callForwardingCondition', $this->CallForwardingCondition->findByType('list'));
In SQL Dump following query is done when page is reloaded:
SELECT `CallForwardingCondition`.`type`, `CallForwardingCondition`.`description` FROM `vpbx`.`call_forwarding_condition` AS `CallForwardingCondition` WHERE `CallForwardingCondition`.`type` = 'list' LIMIT 1
How can I direct Cakephp to findByType which will result in following query?
SELECT `CallForwardingCondition`.`type`, `CallForwardingCondition`.`description` FROM `vpbx`.`call_forwarding_condition` AS `CallForwardingCondition` WHERE `CallForwardingCondition`.`type` LIKE '%' LIMIT 10
For CakePHP 2.x you need to use find('all') and pass it the required conditions and limit:-
$result = $this->CallForwardingCondition->find('all',[
'conditions' => ['CallForwardingCondition.type Like' => '%'],
'limit' => 10
);
findByType is a special find method that will only return the first record matching the type passed as the find method's parameter which is why it isn't returning what you want. You can read more about the findBy magic functions in the official docs.
try this:
$result = $this-> CallForwardingCondition ->find('all',['limit'=>10,'conditions'=>['CallForwardingCondition.type Like'=>'%'])->toArray();
I don't think you can't use findBy with limit. If you want to use limit, you must use findAllBy<fieldName>. Even findAllBy<fieldName>, you can't use LIKE.
This is findAllBy from cakephp
findAllBy<fieldName>(string $value, array $fields, array $order, int $limit, int $page, int $recursive)
So if you want to covert it, you must do the following way;
$this->CallForwardingCondition->findAllByType('something',['CallForwardingCondition.*'],['CallForwardingCondition.id'=>'desc'],'10');
This is findBy from cakephp doc.
findBy<fieldName>(string $value[, mixed $fields[, mixed $order]]);
Hope this help for you.

Filtering parameters in CakePHP

In Rails, we can specify the allowed parameters to be used in the controller when saving data. So, with params being the submitted data, I can do this:
params.require(:person).permit(:name, :age)
Which will ensure that the :person key is present and will filter out anything that is not a person's :name or :age.
Is there any way in CakePHP to accomplish this?
EDIT: I know I can write PHP, I want to know if there's a Cake component / plugin that already does this.
Something in this PHP way:
// submited data
$this->request->data['Person'] = array(
'name' => 'Salines',
'age' => '41',
'job' => 'Web Developer'
);
// check if isset and filter out anything that is not a person's name or age
if(isset($this->request->data['Person']))
{
$permit = array('name' => '','age' => '');
$this->request->data['Person'] = array_intersect_key($this->request->data['Person'],$permit);
}
//and return $this->request->data like
array(
'Person' => array(
'name' => 'Salines',
'age' => '41'
)
);
I'm looking for a Cake-provided solution (if there is one)
Well, define "cake-provided", you mean by the framework itself? No, the core doesn't have this functionality but there are two plugins.
For Cake3: Plum Search
For Cake2 & 3: CakeDC Search
For Cake3 I would go for Plum-Search, it is written by the same person as the initial code of the other plugin but a complete rewrite and makes a better use of Cake3.
Next time you ask name your exact Cake version.
Both plugins implement the PRG pattern but don't explicitly allow or deny query parameters. They'll only grab the parameters you specified in your filter declaration and turn them into the request. Validate and save to exclude unwanted fields.
Make a url link like this
echo $this->Html->url(array('controller'=>'users','action'=>'hello','par1'=>23,'par2'=>'sud'));
In hello function in users controller
pr($this->params->named['par1']);
pr($this->params->named['par2']);

Drupal services module JSON response fetched: Backbone.js model attributes turn into string

I've set up web services using Drupal's services module. It outputs JSON for me which I am requesting through a Backbone.js front-end application.
I'm having issues with this set-up. If I request data through Backbone.js' fetch method of a model, the model's attributes are all typed as string after fetching, while there are some attributes that should be e.g. integer.
For example:
I have enabled the user resource, which is standard available in the Drupal services module
I can request a user, e.g.:
http://mydevmachine/services/user/8
...which results in the following response (slimmed down version from the real response):
{"uid":"8","name":"itsme","mail":"me#mydomain.nl"}
What I see in the response from the web service above, all values are quoted, however uid is really not a string but an integer in the database.
If I fetch the same user in my Backbone.js model, by setting the uid field of my model to 8 (integer), then call the fetch method. After fetching the uid field is typed as 'string'.
I assume the above leads to my model ending up with a uid attribute of not integer, but string. It also happens with all other web service resources I have created, using my own entities.
I need correct typing of attributes in my model due to sorting issues using Backbone's collection sorting. I.e. sorting a collection of models using a field of type 'integer' leads to different sorting results when sorting the field with the same values although stored as a string.
I'm not sure exactly where to look:
Is the JSON format output by the Drupal services module according to standards?
Is the JSON output format configurable or overridable in the Drupal services module?
Is it perhaps possible to keep the type of a model's attribute after a fetch in Backbone.js?
Should I provide a specific implementation for Backbone's collection comparator function, which handles this situation (seems hackey)?
Should I introduce other solutions, e.g. like posted here: How can I enforce attribute types in a Backbone model? (feels too heavy).
Thanks for any help.
So I finally managed to crack this issue and I found my solution here: How to get numeric types from MySQL using PDO?. I thought I'd document the solution.
Drupal 7 uses PDO. Results fetched using PDO, using Drupal's default PDO settings result in stringified values.
In Drupal's includes/database.inc file you will find this around lines 40-50:
$connection_options['pdo'] += array(
// So we don't have to mess around with cursors and unbuffered queries by default.
PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => TRUE,
// Because MySQL's prepared statements skip the query cache, because it's dumb.
PDO::ATTR_EMULATE_PREPARES => TRUE,
);
The statement here that MySQL's prepared statements skip the query cache is not entirely true, as can be found here: http://dev.mysql.com/doc/refman/5.1/en/query-cache-operation.html. It states MySQL > 5.1.17 prepared statements use the query cache under certain conditions.
I used the info from the other stack overflow question/answers to override the PDO settings for the database connection in Drupal's sites/default/settings.php (please note I only did this for the database I was querying, which is different than Drupal's own database):
'database_name' =>
array (
'default' =>
array (
'database' => 'database_name',
'username' => 'user_name',
'password' => 'user_pass',
'host' => 'localhost',
'port' => '',
'driver' => 'mysql',
'prefix' => '',
'pdo' => array(
PDO::ATTR_STRINGIFY_FETCHES => FALSE,
PDO::ATTR_EMULATE_PREPARES => FALSE
),
),
),
This resulted in integers being integers. Floats/decimals are incorrectly returned by PDO still, but this is different issue. At least my problems are solved now.

Dynamically add virtual field in cakephp

I am using CakePHP 2.1.3; I want to create a virtual field dynamically in a controller. Is it possible?
The problem is when I am trying to find max value in a table it gives me another array from the model array. Please ask if you need more information.
When I am trying to execute the following query,
$find_max_case_count = $this->CaseMaster->find('first', array(
'conditions' => array(
'CaseMaster.CLIENT_ID' => $client_id,
'CaseMaster.CASE_NO LIKE' => '%-%'
),
'fields' => array('max(CaseMaster.CASE_NO) AS MAX_NO')
));
It is giving me an array like:
[0]=> array([MAX_NO]=> 52)
However I want it to be like as:
[CaseMaster] => array([MAX_NO] => 52)
I found a solution. I can make the virtual field at runtime. The code should looks like:
$this->CaseMaster->virtualFields['MAX_NO'] = 0;
Write it just above the find query and the query will remain same as it was written.
This link was helpful to find out the solution.
There is no way (as far as I am knowledgeable) to create virtual fields "on the fly". What virtual fields are is "arbitrary SQL expressions" that will be executed when a find runs through the Model and "will be indexed under the Model's key alongside other Model fields".
What do you need to do with "dynamically created virtual fields"? If you explain what exactly you need to accomplish maybe we can provide a different (even more suitable? :) ) solution? I'd personally be happy to help you.
After you editing your question I can say that what you're getting is the way the array should be returned, this is because of the fields parameter. If you want to get a different structure out of it I suggest applying a callback to format it.
Firstly move the method inside the CaseMaster Model:
public function getMaxCaseCount($client_id){
$data = $this->find('first', array(
'conditions' => array(
'CaseMaster.CLIENT_ID' => $client_id,
'CaseMaster.CASE_NO LIKE' => '%-%'),
'fields' => array('max(CaseMaster.CASE_NO) AS MAX_NO')));
return array_map(array('CaseMaster', '__filterMaxCaseCount'), $data);
}
private function __filterMaxCaseCount($input){
//This is just an example formatting
//You can do whatever you would like here.
$output['CaseMaster'] = $input[0];
return $output;
}
The array_map function will apply the __filterMaxCaseCount callback method so that when you call:
$this->CaseMaster->getMaxCaseCount($client_id);
from your controller you will get the data in the way you need it. The array_map function could also look like this:
return array_map(array($this, '__filterMaxCaseCount'), $data);
because you're in the same Class.
Just adding your model alias to field definition also works for this purpose
'fields' => array('max(CaseMaster.CASE_NO) AS CaseMaster__MAX_NO')

array to Zend_Db_Table_Row zend framework

is there a way of automatic converting from array to Zend_Db_Table_Row or Zend_Db_Table_Rowset?
Form Zend_Db_Table_Row you can get the array with toArray(), but I was wondering if there exits anything like opposite of that?
Till now I have been implementing a function fill($data) which took the array and than set the atributes of Zend_Db_Table_Row.
Of course array keys are the same as Zend_Db_Table_Row attributes.
Thanx!
Check the Zend_Db_Table's fetchRow() method. There you can find it. I guess you can feed the array to the constructor like this:
$data = array(
'table' => $yourDbTableModel,
'data' => $yourArray,
'readOnly' => $iGuessShouldBeZero,
'stored' => true
);
$row = new Zend_Db_Table_Row($data);
I think this should do the trick:
$myRow = new Zend_Db_Table_Row(
array(
'data' => array( /* your array with data */ )
)
);
So, if you provide the constructor with a config array that holds a key 'data' that in it's turn holds an array with the data, you should be good.
For more info look into Zend_Db_Table_Row_Abstract in your Zend library.

Resources