cakePHP last-fm datasource
Jan 12, 2010
I couldn't find a simple existing cake solution for interfacing with last.fm, so I put together a cakePHP datasource for connecting up to lastfm. At the moment, i've only implemented the getrecenttracks last-fm method (will update soon).
in /app/config/database.php I added the authentication details as per last-fm's api requirements:
Show Plain Text- 'datasource' => 'lastfm',
- 'apikey' => 'APIKEY!',
- 'secret' => 'SECRET!'
- );
Next, in /app/models/datasources i added my datasource (create the file lastfm_source.php):
Show Plain Text- <?php
- /**
- * @desc ultra-simple last-fm datasource
- * @author joshskeen
- * @version .1
- * @filename lastfm_source.php
- **/
- class LastfmSource extends DataSource {
- var $secret = '';
- var $apikey = '';
- var $Http = '';
- var $base_url = '';
- 'apiHost' => 'http://ws.audioscrobbler.com/',
- 'apiPath' => '2.0/'
- );
- function __construct($config) {
- parent::__construct($config);
- $this->Http =& new HttpSocket();
- $this->secret = $this->config['secret'];
- $this->apikey = $this->config['apikey'];
- $this->base_url = $this->_baseConfig['apiHost'] . $this->_baseConfig['apiPath'];
- }
- function get_recent_tracks($user, $limit=5){
- 'limit' => $limit,
- 'user' => $user,
- 'api_key' => $this->apikey)));
- }
- function __process($response) {
- $xml = new XML($response);
- $array = $xml->toArray();
- $xml->__killParent();
- $xml->__destruct();
- $xml = null;
- return $array;
- }
- }
- ?>
And here's a controller demonstrating its use (in /app/controllers/lastfms_controller.php). Notice, i go the route of disabling the model by setting the $uses var to null, since I'm using my datasource instead of an actual model.
Show Plain Text- <?php
- class LastfmsController extends AppController {
- var $uses = null;
- function index(){
- $this->pageTitle = 'Recently scrobbled';
- $tracks = $this->getRecentTracks('mutexKid', 15);
- $this->set('lfm_tracks', $tracks['Lfm']['Recenttracks']['Track']);
- }
- function getRecentTracks($user, $limit){
- $this->Lastfm = ConnectionManager::getDataSource('lastfm');
- return $this->Lastfm->get_recent_tracks($user, $limit);
- }
- }
- ?>