How to save a chain of scopes to reuse it multiple times - pointers

The way I'd like to write code:
$chain = Articles::model()->visible()->childOf($teleshow_id);
echo $chain->count( $criteria );
// 1st echo - will write the amount of visible articles,
// which are children of $teleshow_id
echo $chain->count( $criteria );
// this echo will write the amount of all articles
But I'd like to get identical results of echos.
Is there any solution to keep $chain persistent ( to work with not a pointer to Articles::model()->visible()->childOf($teleshow_id) )

You could try something like the following:
// in your Articles class
private $_chain;
public function getChain($teleshow_id = false)
{
if(!isset($this->_chain))
{
$chain = Articles::model()->visible()->childOf($teleshow_id);
}
return $this->_chain;
}
and then call it from your controller like this:
$model = new Articles();
$chain = $model->getChain($teleshow_id);
$model->chain->count();
or something similar. You may need to mess with making getChain static if you want to make your calls easier, but you should be able to get started with that.

Related

Array as parameter in Doctrine SQLFilter

I'm trying to create Doctrine SQLFilter. I need to filter for "deleted" field. But i want to make filter works with both (true and false) values too.
Something like this:
<?php
namespace Rem\CostsBundle\Doctrine;
use Doctrine\ORM\Mapping\ClassMetadata;
use Doctrine\ORM\Query\Filter\SQLFilter;
class ItemDeletedFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
if ($targetEntity->getReflectionClass()->name != 'Rem\CostsBundle\Entity\Item') {
return '';
}
$fdata = $this->getParameter('deleted');
$filter = '1<>1';
foreach ($fdata as $param) {
$filter .= sprintf('OR %s.deleted = %s', $targetTableAlias, $param);
}
return $filter;
}
}
But when I'm trying to set array of posible filter values in controller
$filters
->enable('costs_item_deleted')
->setParameter('deleted', [true, false]);
I get an error 500
Warning: PDO::quote() expects parameter 1 to be string, array given
This is clear situation. But, after all HOW to send array of params to my SQL filter?
UPD after Dmitry answer: This is not actualy what I wanted. Let say: what if I wanted to filter by few values of field? For records of 2015 and 2016 years for example... So i need to set some sort of array-of-years in ->setParameter. But it want only strings! And sends an error when i'm trying to set something else.
How do you solve this?
Or even more complicated example. What if I need to filter by relational field. In this case I need to set entity as param of filter. Or even ArrayCollection of entities!
For now I'm decide it like this: I json_encode array before set it to setParameter in controller. And then I json_decode it in Filter class. BUT! There in Filter class I need to make one more step. I need to remove single and doublequotes from json string. Because they was added by setParameter to escape string (thats why we love it )) ).
Code hacks like this we call "crutches" here in Russia. So I'd like to avoid of them and write more elegant code )
Make it IN instead of comparing.
foreach ($fdata as $param) {
$filter .= sprintf('OR %s.deleted IN (%s)', $targetTableAlias, param);
}

How to remove galleryhasmedia from gallery sonatamediabundle

I am trying to remove galleryhasmedia from gallery.
However gallery entity doesn't have removegalleryhasmedia or something.
so I did a clumsy way, but it doesnt work.
$em = $this->getDoctrine()->getManager();
$firstGhmArray = $gallery->getGalleryHasMedias();
echo count($gallery->getGalleryHasMedias()) // before count
$afterGhmArray = array();
foreach ($firstGhmArray as $ghm){
if ($ghm->getId() == $id){ // id is the target id to delete
//delete
}
else {
array_push($afterGhmArray , $ghm);
}
$gallery->setGalleryHasMedias($afterGhmArray);
}
echo count($gallery->getGalleryHasMedias()) // after count
$em->persist($gallery);
$em->flush();
I think if galleryHasMedias are normal array collection.
I can delete the element with this procedure.
I need to do something more for galleryhasmedia??
You can override the Gallery entity and add this function to it :
public function clearGalleryHasMedias()
{
$this->galleryHasMedias->clear();
}
galleryHasMedias field is an ArrayCollection which can be cleared using the clear method. Its weird tho that setting an empty array doesn't clear work but i guess my solution is worth the shot.

Laravel Eloquent - Encrypting/Decrypt Data on call

I can use Crypt to encrypt/decrypt my data. I want to encrypt some information in my db (such as the name, email, phone number to name a few).
Assuming that I want EVERYTHING to be encrypted, I want to be able to do this in the background by itself, which I can perform by overwriting the create and save functions:
// For instance, the save() function could become
public function save(array $options = array())
{
foreach ($this->attributes as $key => $value)
{
if (isset($value)) $this->attributes[$key] = Crypt::encrypt($value);
}
return parent::save($options);
}
Now, I want the decryption to be performed the same way, so that when I say User::find($id), the returned $user is already decrypted. Also other functions such as firstOrFail() get() first() and all to work as well.
I also would like this functionality to be extended when I use relationships (so User::with('someOtherTable')->find($id) also work).
Would this be possible? If this is not possible, I am thinking of creating a helper function decyrpt()
function decrypt($array)
{
if (!is_array($array)) return Crypt::decrypt($array);
$result = [];
foreach($array as $key => $value) $result[$key] = decrypt($value);
return $result;
}
And pass all my results through this first, and then start using them, but it would be nicer if Laravel would provide this, or if there was a "Laravel Way" of doing this.
It doesn't really make sense to encrypt everything. For example, you never want to encrypt the primary key; that doesn't even make sense. Likewise you probably don't want to encrypt the date fields; you'll lose the ability to perform any sort of SQL query on them.
With that in mind, you can try something like this:
class BaseModel extends Eloquent {
protected $encrypt = [];
public function setAttribute($key, $value)
{
if (in_array($key, $this->encrypt))
{
$value = Crypt::encrypt($value);
}
return parent::setAttribute($key, $value);
}
public function getAttribute($key)
{
if (in_array($key, $this->encrypt))
{
return Crypt::decrypt($this->attributes[$key]);
}
return parent::getAttribute($key);
}
public function attributesToArray()
{
$attributes = parent::attributesToArray();
foreach ($attributes as $key => $value)
{
if (in_array($key, $this->encrypt))
{
$attributes[$key] = Crypt::decrypt($value);
}
}
return $attributes;
}
}
then have all you models extend this one, and set the $encrypt property to whatever columns you want encrypted for that particular model.
P.S. If you want to use Eloquent's accessor functionality, you'll have to play with this a bit more.
It's worth mentioning Elocrypt library for Laravel 4. It's a more elaborate solution that works the same way. If you're using Laravel 5 use this one instead: Elocrypt 5.

Why is my function in Wordpress not working?

Why not work my function in wordpress?
My code
add_post_meta( $ids, 'price', $price, true );
$price_add = get_post_meta($id, 'price', true);
function myprice(){
if ($price_add != ' '){
echo $price_add." Euro";
}
else {
echo "None";
}
}
I try use if (isset($price_add)) but not work.
I want to show price introduced in or show text "None".
You are attempting to use a variable which is not "in scope". You might want to read the PHP manual page on variable scope.
A function is a reusable piece of code, with input and output, and in PHP variables are "scoped" (visible) to the function they are declared in. (The main exception is global variables, which are usually frowned on as they make code hard to read, reuse, and test; static variables and object members work a bit differently.)
In your case, you want a function which takes as input a price, and echoes that price if it is not an empty string (or, as you've written it, a single space); you might define that like this:
function myprice($price_to_display) {
if ($price_to_display != ' '){
echo $price_to_display." Euro";
}
else {
echo "None";
}
}
You then call that somewhere else, passing in the value you want to display, like this:
$price_add = get_post_meta($id, 'price', true);
myprice($price_add);
Note that I've named the variable in the function something different for clarity; you could call it $price_add, but that wouldn't make it connected to the other variable called $price_add in any special way.
[Edited to add...] In fact, you don't need to have a variable at all when you are calling the function - what you are providing is a value for the input parameter. So you could also write it like this:
myprice( get_post_meta($id, 'price', true) );

recursive function using joomla db object

I want to write a recursive function in joomla that get all the child level categories using a category id using joomla's jmodel's db object.Following is my code that I have written:
function getChildCategories($type){
$query = "SELECT id FROM #__cd_categories WHERE parent_id='$type'";
echo $query."<br/>";
$this->_db->setQuery($query);
$list = $this->_db->loadObjectList();
if ($this->_db->getErrorNum()) { echo $this->_db->stderr(); return false; }
foreach($list as $record){
$this->childCategories[]= $record->id;
echo $record->id."<br/>";
return $this->getChildCategories($record->id);
}
return true;
}
So now problem is that, in joomla we use $this->_db_setQuery method and $this->_db->loadObjectList method , so in recursive call the result set, I think it overwrite, I think because the object is same. So can any one tell the way that how to overcome this problem? If you can solve this by using loop even that would be also very helpful for me.
I also think that once values are assigned to $list variable then that over write shouldn't be problem.So seems strange.Please tell if some one can tell me the way to do it?
thanks in advance
I don't think the issue is with the database object getting overwritten. It has been a bit since I have been struggling with recursive functions but I think the issue is with assigning the $list variable.
Should you not be returning that variable instead of boolean true like this:
function getChildCategories($type) {
$query = "SELECT id FROM #__cd_categories WHERE parent_id='$type'";
$this->_db->setQuery($query);
$list = $this->_db->loadObjectList();
if ($this->_db->getErrorNum()) { echo $this->_db->stderr(); return false; }
if ($list) {
foreach($list as $record){
$list->childCategories = $this->getChildCategories($record->id);
}
return $list;
} else {
return;
}
}

Resources