This blogpost is focused on CakePHP 1.2 / 1.3
I don’t have to explain why CakePHP is such a brilliant PHP framework.. The good part with frameworks is that they include a rich reusable API library full of functions that will make life easier for most programmers. CakePHP is such a framework with an enormous rich library. I only know half of the functions but every day I discover some new great functions which some of them I want to share.
After I wrote an article about how we built Twittermail in 48 hours, Matt from PseudoCoder.com wrote a blogpost about Httpsocket. I was constantly using the curl library from PHP, I just did not know CakePHP had it’s own ‘grabber’ included. It’s called Httpsocket, it’s a core Utility library and it’s quite interesting what the possibilities are. I truly love curl because they have many functions like handling cookies, auto follow header locations and other very handy stuff. But for quick calls it’s just as easy to use the CakePHP Httpsocket. Here’s an example:
To simply get my LastFM timeline, I only need:
You can be much more specific with the Httpsocket library like giving a User Agent or supplying user authentication.
2. Convert an Object into an Array
For data I prefer array’s more than objects. To get my LastFM timeline I need to retrieve an XML file. I always used simplexml_load_string to convert the results to an XML object. After that I had to convert the object to an array and therefore I used a custom function I found on php.net. Lately I discovered the beautiful ‘Set’ Core library from CakePHP. In the Set Core Utility library there are some very useful functions to manipulate arrays and objects. One of the functions is called Reverse, and this function is doing exactly what I want in just 1 line:
3. The XML library Coming to the next point, the XML library. I did not know CakePHP had an XML core library and that’s why I had to use ‘simplexml_load_string‘. With the XML library you can easily convert a string to an XML object.
You can even get a remote XML file by using an URL!
I just love cache, I use it quite often and can’t live without it. The only problem is that when I use Cache::write(), in the past I could always tell this function for how long it should be cached. For some reason this is not working anymore and you need to supply a config name. In my core.php file I told some configs for how long it should be cached. Today I found out I can tell the cache on the fly for how long it should be cached! Using Cache::set()!
5. String insert
Most of my projects I prepare for Internationalization so it will be easy to add more languages in the future. Therefore I’m using the __(‘Hello!’) function for every text I need. But what if you need data in your text like a name or an age. You can use sprintf and the %s signs in the text, but I just think that’s not so nice in the PO files. By using String insert you have a more accessible text in your PO files which is easier to understand for translators.