Blog

CakePHP

Sometimes when a user requests to download a file from your app you may want to run some pre-download logic. For example, you may want to check that the user is authenticated or perhaps log the download. Since CakePHP 2.3 this can be simply achieved using CakeResponse.

Generating a downloadable CSV file in CakePHP seems to be a bit of a stumbling block for many relatively new to using Cake. It doesn’t need to be challenging. There’s just a few basic steps you need to put in place.

As an example we’ll consider a Subscriber model that contains contact details of people who have subscribed to our app. We want to create a CSV export of all the subscribers data.

When using CakePHP’s (v2.x) saveAll method on a model you may have found that the afterSave callback for the model isn’t being called after everything has saved. Instead it is called just after the primary model is saved and before saving the associated model data. This can be a bit of a problem if you want to play around with the data from the associated models being saved in the saveAll. The way to get around this is to extend the saveAll method and create a new callback, afterSaveAll.