Yii relations result non-existing items (cache issue?) - caching

I have set relations: 'teamDrivers' => array(self::HAS_MANY, 'TeamDriver', 'team_id') in my Team model
So if I want I can: print_r($this->teamDrivers); in my Team. Just for demonstration.
Now the problem is that this kind of code produces a list of items that have already been removed form database! Via CActiveDataProvider with CDbCriteria those items are not reached.
If I log out from my app and then log back in everything seems to be working.
So is there some cache that takes care of those relations or what is this mystery? And how do I clear that cache?

In my case UserIdentity object had old information and team was got through it. Refreshing was the solutions.

Related

Laravel - trouble with Eloquent Collection methods such as last()

I have a variable $courses that in my debugger is shown as type App/Courses
In the model, there is a one to many relation and I retrieve these related items in the model and then access as $courses->relateditems
In the debugger, $courses->relateditems is shown as type Illuminate/Database/Eloquent/Collection
Ok, all makes sense.
I want to get last item in the $courses->relateditems collection. So I try
$courses->relateditems->last()->startdate
But this is not returning the value that I know exists. And when I evaluate the expression $courses->relateditems->last() in the debugger I get this in my laravel.log:
Symfony\Component\Debug\Exception\FatalErrorException: Cannot access self:: when no class scope is active in /app/Courses.php:68
I am just not sure what is going on. I know I can use DB queries to just get the data I need, but I have a model event triggering a function and that function receives the $courses object/model (or however we name it) and I am just trying to get this working as above.
Ideas on what I am doing wrong?
thanks,
Brian
The issue here based on the error you have at the bottom of your post is a mistake in your code.
However, I think you've misunderstood how Laravel relationships work. They essentially come in two forms on a model, that of a property and that of a method.
relateditems Is a magic property that will return the result of a simple select on the relationship if one has already been performed. If one hasn't been performed it will perform one and then return it, known as eager loading.
relateditems() Is a method that returns a query builder instance for that relationship.
By calling relateditems->last() you're loading ALL related items from the database and then getting the last, which is less than optimal.
The best thing for you to do is this:
$course->relateditems()->orderBy('id', 'desc')->first();
This will get the first item return, however, since we've ordered it by id in descending order, it'll be reversed from what could be considered its default ordering. Feel free to change the id to whatever you want.

What to store in a notification?

I'm currently utilizing Laravels notification package a bit more, but the following bothers me for weeks now: What should I really store in notifications?
Sometimes notifications are related to specific models, but not always.
Examples: Your blog post was published. or An error occurred while doing something. The entry was deleted.
Sometimes these models have relationships like Post → Category and the message should look like: Your blog post in the category "A Category" was published.
Now the questions:
Should I save a related model completely (eg. Category)? This would make accessing it later easier, but it's also a source for inconsistency. Or should I simply save the category ID? Only saving the ID means that I can reference the current data, but what happens if the category gets deleted? Then the notification cannot be rendered. Also I would need to also query the related models for this notification everytime.
Should I save the full message or only the data and compose the message on the client? (App, SPA Web-Frontend...). What about localization then?
What is a best practice for future scaling and also for extending existing notifications in the future?
So you propose to either go for:
1. Save notifications including all data required to display it
OR
2. Save notifications with just references so it can render message later on
So let's consider the advantages and drawbacks of both options.
Option 1: saving including all data
If a related model is deleted, the notification message can still be rendered as before (as you mentioned)
If a related model is changed (e.g. category title is changed), the notification message does not change
If you want to change a notification later on to include additional fields from related models, you won't have those fields available
Option 2: saving including just references
If a related model is deleted, the notification can not be rendered (as you mentioned). I would however argue that the notification wouldn't make much sense in this case.
If a related model is changed (e.g. category title is changed), the notifciation message changes with it
If you want to change a notification later on to include additional fields from related models, you will have those fields available
Additionaly if you were to serialize the notifications in the database you won't be able to deserialize them if you changed the model for it later on (e.g. a field is deleted).
Implementation of option 2
In order to go for option 2 additional database load can't really be avoided.
Easy way
The easiest way would be to resolve the relationships in the notification would be to query the relationships during the rendering of the notifications array, this however will cause the system to an additional query for each relationship.
NotificationController.php
$user = App\User::find(1);
foreach ($user->notifications as $notification) {
echo $notification->type;
}
MyNotification.php
public function toArray($notifiable)
{
$someRelatedModel = Model::find($this->someRelatedModel_id);
return [
'invoice_id' => $this->invoice->id,
'amount' => $this->invoice->amount,
'relatedModelData' => $someRelatedModel->data,
];
}
Nicer way
The better solution would be to adjust the query currently used for retrieving the notifications so it will include the relationships on the initial load.
NotificationController.php
$notification = App\Notification::byUserId(1)->with('someRelatedModel);
See eager loading for more on this.
Tl;dr Considering the points above I'd go with option 2; only keep references to models you'll need when rendering the notification.

cakephp 2.1 view associated data across all add.ctp, edit.ctp, view.ctp

I have an "examinations" table, its consultation_id relates to "consulsations" table, which in turn its consulation_id relates to the "patients" table.
Now, when I am in the add.ctp, edit.ctp or view.ctp of the "Examinations" Views I need to pull the "patients" details in so that some patient info can appear as to who the form pertains to as patient.
I have tried joins. Not to say they dont work. I am new to cakephp and I really need help as to how it will appear within the controller and how the view.ctp will display it.
I thought of elements but they are just .ctp files right?
Please if anyone can help regarding this it would be so appreciated. I've been trying to do this now for a week and I know there is something simple I am dont doing or thinking rights about.
So you just want to pull in related data? Pretty simple.
In your ExaminationsController methods.
$patients = $this->Examination->Consultation->Patient->find('all',
array('conditions'=>array('consultation_id'=>$id,'examination_id'=>$e_id)));
Something similar to this, not quite sure on which id you need to pass, as it will depend on how your models are linked up. http://book.cakephp.org/2.0/en/models/retrieving-your-data.html
However, if your models are linked up properly, you should get this data anyway. If not set your models recursion to be higher.
$this->Model->recursive = 2;

Doctrine2 Caching of updated Elements

I have a problem with doctrine. I like the caching, but if i update an Entity and flush, shouldn't doctrine2 be able to clear it's cache?
Otherwise the cache is of very little use to me since this project has a lot of interaction and i would literally always have to disable the cache for every query.
The users wouldn't see their interaction if the cache would always show them the old, cached version.
Is there a way arround it?
Are you talking about saving and fetching a new Entity within the same runtime (request)? If so then you need to refresh the entity.
$entity = new Entity();
$em->persist($entity);
$em->flush();
$em->refresh($entity);
If the entity is managed and you make changes, these will be applied to Entity object but only persisted to your database when calling $em->flush().
If your cache is returning an old dataset for a fresh request (despite it being updated successfully in the DB) then it sounds like you've discovered a bug. Which you can file here >> http://www.doctrine-project.org/jira/secure/Dashboard.jspa
Doctrine2 never has those delete methods such as deleteByPrefix, which was in Doctrine1 at some point (3 years ago) and was removed because it caused more trouble.
The page http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/caching.html#deleting is outdated (The next version of the doctrine2 document will see those methods removed). The only thing you can do now is manually managing the cache: find the id and delete it manually after each update.
More advanced doctrine caching is WIP: https://github.com/doctrine/doctrine2/pull/580.
This is according to the documentation on Doctrine2 on how to clear the cache. I'm not even sure this is what you want, but I guess it is something to try.
Doctrine2's cache driver has different levels of deleting cached entries.
You can delete by the direct id, using a regex, by suffix, by prefix and plain deleting all values in the cache
So to delete all you'd do:
$deleted = $cacheDriver->deleteAll();
And to delete by prefix, you'd do:
$deleted = $cacheDriver->deleteByPrefix('users_');
I'm not sure how Doctrine2 names their cache ids though, so you'd have to dig for that.
Information on deleting cache is found here: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/caching.html#deleting
To get the cache driver, you can do the following. It wasn't described in the docs, so I just traced through the code a little.
I'm assuming you have an entity manager instance in this example:
$config = $em->getConfiguration(); //Get an instance of the configuration
$queryCacheDriver = $config->getQueryCacheImpl(); //Gets Query Cache Driver
$metadataCacheDriver = $config->getMetadataCacheImpl(); //You probably don't need this one unless the schema changed
Alternatively, I guess you could save the cacheDriver instance in some kind of Registry class and retrieve it that way. But depends on your preference. Personally I try not to depend on Registries too much.
Another thing you can do is tell the query you're executing to not use the result cache. Again I don't think this is what you want, but just throwing it out there. Mainly it seems you might as well turn off the query cache altogether. That is unless it's only a few specific queries where you don't want to use the cache.
This example is from the docs: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/caching.html#result-cache
$query = $em->createQuery('select u from \Entities\User u');
$query->useResultCache(false); //Don't use query cache on this query
$results = $query->getResult();

How to cache a collection in Magento?

I have a collection that takes significant time to load. What I would like is to cache it (APC, Memcache). It is not possible to cache the entire object (as it cannot be unserialized and it is over 1 MB). I'm thinking that caching the collection data ($col->getData() ) is the way to go, but I found no way to rebuild the object based on this array. Any clues?
Collections already have some caching built in but they need a little prompting so put this in the constructor of a collection:
$cache = Mage::app()->getCacheInstance();
$prefix = "SomeUniqueValue";
$this->initCache($cache, $prefix, array(Mage_Catalog_Model_Product::CACHE_TAG));
Choose tags appropriate to the content of the collection so that it will be flushed automatically. This way builds an ID based on the query being executed, it is most useful when the collection is filtered, ordered or paged - it avoids a version conflict.
Generally this hardly gets used because when you retrieve data you almost always end up displaying it, probably as HTML, so it makes sense to cache the output instead. Block caching is widely used and better documented.
I really don't know, but I searched for all the files that have the word "cache" in them with file names of "Collection.php" and got a few results. The most promising example to look at might be Mage_Sales_Model_Entity_Quote_Item_Collection (_getProductCollection() method). Looks like Varien_Data_Collection (which is a parent class of any magento collection) has a few cache-related methods: initCache() and _getCacheInstance().
Can't say I have used them before but might be useful someday.
Good luck.
You can get more information here: Can I use Magento's Caching layer as a Key/Value Store?
I'll be posting more info there as I find it.

Resources