Yii 1.1: eimdbquery

A wrapper for IMDB API on http://www.imdbapi.com
4 followers

A wrapper for IMDB API on http://www.imdbapi.com.

Requirements

  • Yii 1.1.
  • CURL or fopen enabled in server.

Usage

  • Download the extension and extract it to your extension directory.
  • Just follow the following example:
<?php
    // Load the extension
    Yii::import("ext.EImdbQuery.EImdbQuery");
 
    // Create the object
    $movie = new EImdbQuery($model->Title, EImdbQuery::TYPE_TITLE);
 
    // Get data as a property, or
    $movie->Title
 
    // Get data as a method
    $movie->getTitle();
 
        // Alternatively, to do a search.
    $movie = new EImdbQuery($model->Title, EImdbQuery::TYPE_TITLE, false); // set last parameter to false, which defines to do a less strict search
 
    $movie->Greedy = true; // set to true to get all complete results for each movie
 
    // Get results
    for($i=0;$i<$movie->getCount();$i++)
    {
        // Get data as a method
        $movie->getTitle($i);
    }
 
    // Get data as a property
    $movie->Title_0
?>

Available Data

  • Title
  • Year
  • Rated
  • Released
  • Runtime
  • Genre
  • Director
  • Writer
  • Actors
  • Plot
  • Poster
  • imdbRating
  • imdbVotes
  • imdbID
  • Response

Contact

Any bugs or suggestions could be delivered to me through bS.xx7_37@yahoo.com.

Total 1 comment

#19233 report it
Fire at 2015/04/25 03:45am
hi there, I have made a small fix to your code

Hi there, i added a TYPE_SEARCH so that the user can search easier using your api

<?php /** * EImdbQuery. * A wrapper for IMDB API on http://www.imdbapi.com * * @author Syakur Rahman bS.xx7_37@yahoo.com * @license New BSD License * @version 1.0 * @example * <?php // Load the extension Yii::import("ext.EImdbQuery.EImdbQuery"); // Create the object $movie = new EImdbQuery($model->Title, EImdbQuery::TYPE_TITLE); // Get data as a property, or $movie->Title // Get data as a method $movie->getTitle(); // Alternatively, to do a search. $movie = new EImdbQuery($model->Title, EImdbQuery::TYPE_TITLE, false); // set last parameter to false, which defines to do a less strict search $movie->Greedy = true; // set to true to get all complete results for each movie // Get results for($i=0;$i<$movie->getCount();$i++) { // Get data as a method $movie->getTitle($i); } // Get data as a property $movie->Title_0 ?> * * Available data: * Title Year Rated Released Runtime Genre Director Writer Actors Plot Poster imdbRating imdbVotes imdbID Response */ class EImdbQuery { /** * Defines the data type for retrieving values from API. * @var enum Accepted values: EImdbQuery::DATA_JSON, EImdbQuery::DATA_XML */ public $DataType = self::DATA_JSON;

/**
 * Defines whether to recieve a short or full plot of movie.
 * @var enum Accepted values: EImdbQuery::PLOT_SHORT,  EImdbQuery::PLOT_LONG 
 */
public $Plot = self::PLOT_SHORT;

/**
 * Defines whether to show errors with exception or a string message.
 * @var boolean 
 */
public $ShowNoneAsException = false;

/**
 * Defines the value that would be shown when the given title of movie isn't found.
 * @var string 
 */
public $NaValue = "Data N/A.";

/**
 * Defines whether to get all complete fields from a search result or not.
 * @var boolean
 */
public $GreedyMode = true;

/**
 * Constant for retrieving short plot.
 */
const PLOT_SHORT = "short";

/**
 * Constant for retrieving full plot.
 */
const PLOT_LONG = "full";

/**
 * Constant for retrieving data in JSON format.
 */
const DATA_JSON = "JSON";

/**
 * Constant for retrieving data in XML format.
 */
const DATA_XML = "XML";

/**
 * Constant for id GET parameter.
 */
const TYPE_ID = "i";

/**
 * Constant for title GET parameter.
 */
const TYPE_TITLE = "t";
/**
 * Constant for search GET param
 */
const TYPE_SEARCH = "s";
/**
 * Url of the API.
 * @var string 
 */
private $_serviceUrl = "http://www.omdbapi.com";

/**
 * Url of the detail page of a movie.
 * @var string 
 */
private $_detailUrl = "http://www.imdb.com/title/";

/**
 * GET parameter that would be use to identify year.
 * @var string
 */
private $_paramYear = "y";

/**
 * GET parameter that would be use to identify return data type.
 * @var string 
 */
private $_paramDataType = "r";

/**
 * GET parameter that would be use to identify how the plot would be returned.
 * @var string 
 */
private $_paramPlot = "plot";

/**
 * GET parameter that would be use to identify the search keyword.
 * @var string
 */
private $_paramSearch = "s";

/**
 * Stores data from API. 
 * @var array
 */
private $_data = array();

/**
 * Creates a new instance of the EImdbQuery object.
 * 
 * @param string $Title Movie title that would be queried.
 * @param string $Type Type of inputted data. Accepted values: EImdbQuery::TYPE_TITLE, EImdbQuery::TYPE_ID
 * @param string $Year The year of the movie.
 * @param boolean $StrictMode Determines whether given title is strictly as it is or do a search with it. Default: true.
 * @throws CException
 *
 */
public function EImdbQuery($Title = "", $Type = self::TYPE_TITLE, $Year ="", $StrictMode = true) {
    if ($Title == "" | is_null($Title)) {
        throw new CException("Title can't be empty.");
    }

    if (!in_array($Type, array(self::TYPE_ID, self::TYPE_TITLE, self::TYPE_SEARCH))) {
        throw new CException("Type is invalid, must be i for id, t for title, or s for search");
    }

    $this->_data = $this->_getMovieDataFromAPI($Title, $Type, $Year, $StrictMode);

    if(!$StrictMode)
    {
        $this->_data = $this->_data["Search"];

        if($this->GreedyMode)
        {
            for($i=0;$i<count($this->_data);$i++)
            {
                $this->_data[$i] = $this->_getMovieDataFromAPI($this->_data[$i]['imdbID'], self::TYPE_ID, "", false);
            }
        }
    } else
    {
        $tmp = $this->_data;
        $this->_data = null;
        $this->_data[] = $tmp;
    }
}

private function _getMovieDataFromAPI($Title, $Type, $Year, $StrictMode)
{
    $url = $this->_generateUrl($Title, $Type, $Year, $StrictMode);
    if(function_exists('curl_init'))
    {
        Yii::trace("Using curl to get URL content.");
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        curl_close($ch);
    }else if(ini_get('allow_url_fopen') != false || ini_get('allow_url_fopen') != "")
    {
        Yii::trace("Using fopen to get URL content.");
        $output = file_get_contents($url);
    } else {
        throw new CException("No available method found in server to get URL content. Check server for fopen or curl support.");
    }

    $data = null;
    if($this->DataType == self::DATA_JSON)
    {
        Yii::trace("Reading data as JSON.");
        $JSON = new CJSON();
        $data = $JSON->decode($output, true);
    } else
    {
        Yii::trace("Reading data as XML.");
        $data = reset(get_object_vars(simplexml_load_string($output)->movie));
    }

    return $data;
}

/**
 * Magic call method. Automatically binds to data from API.
 * @param string $name 
 * @param array $arguments 
 * @return mixed 
 */
public function __call($name, $arguments) {
    if(substr($name, 0, 3) == "get")
    {
        $propertyname = substr($name, 3);
        if($this->isMovieFound())
        {
            if(count($arguments>0))
                return $this->_getMovieData($propertyname, reset($arguments));
            else
                return $this->_getMovieData($propertyname);
        } else {
            return $this->_naAction();
        }
    } else {
        throw new CException("Method $name is invalid.");
    }
}

/**
 * Magic get method. Automatically binds to data from API.
 * @param string $name
 * @return mixed 
 */
public function __get($name)
{
    if($this->isMovieFound())
    {
        $index = 0;
        $delimiter = "_";
        if(stripos($name, $delimiter) !== false)
        {
            $tmp = explode($delimiter, $name);
            $index = $tmp[1];
            $name = $tmp[0];
        }

        return $this->_getMovieData($name, $index);

    } else {
        return $this->_naAction();
    }
}

/**
 * Determines whether the movie is found or not.
 * @return boolean
 */
public function isMovieFound()
{
    return ( is_array($this->_data[0]) && !in_array("False",$this->_data[0]) > 0 ) ? true : false;
}

/**
 * Returns total data count
 * @return integer
 */

public function getCount()
{
    return count($this->_data);
}

/**
 * A wrapper for the action when a movie isn't found.
 * @return string
 */
private function _naAction()
{
    if($this->ShowNoneAsException)
    {
        throw new CException("Movie was not found.");
    } else {
        return $this->NaValue;
    }
}

/**
 * Generates the detail url
 * @param type $encode
 * @return string 
 */
public function getDetailUrl($encode = true, $index = 0) {
    if($this->isMovieFound())
    {
        $url = $this->_detailUrl . $this->_data[$index]['imdbID'];
        if ($encode) {
            $url = urlencode($url);
        }
    } else {
        return $this->NaValue;
    }
    return $url;
}

/**
 * Gets individual movie data from array store.
 * @param string $propertyname
 * @return string 
 */
private function _getMovieData($propertyname, $index=0)
{   
    if(array_key_exists($propertyname, $this->_data[$index]) || array_key_exists(strtolower($propertyname), $this->_data[$index]))
    {
        return isset($this->_data[$index][$propertyname])?$this->_data[$index][$propertyname]:$this->_data[$index][strtolower($propertyname)] ;
    } else {
        throw new CException("Property $propertyname is invalid.");
    }
}

/**
 * Generates the api call URL.
 * @param string $Title
 * @param enum $Type
 * @param string $Year
 * @return string 
 */
private function _generateUrl($Title, $Type, $Year = "", $Strict = true) {
    $url = $this->_serviceUrl; // http://www.imdbapi.com
    $url .= "/?";               // http://www.imdbapi.com/?
    if($Strict)
        $url .= $Type . "=" . $Title; // http://www.imdbapi.com/?t=Iron+man&y=2010&plot=short&r=JSON
    else
    {
        if($Type == self::TYPE_ID)
            $url .= $Type . "=" . $Title;
        else if($Type == self::TYPE_SEARCH)
            $url .= $this->_paramSearch . "=" . $Title;
    }
    if (is_numeric($Year)) {
        $url .= "&" . $this->_paramYear . "=" . $Year;
    }
    $url .= "&" . $this->_paramPlot . "=" . $this->Plot;
    $url .= "&" . $this->_paramDataType . "=" . $this->DataType;

    return str_replace(" ", "+", $url);
}

/**
 * Converts an array to an object.
 * @param array $array
 * @return object 
 */
private function _arrayToObject($array) {
if(!is_array($array)) {
    return $array;
}

$object = new stdClass();
if (is_array($array) && count($array) > 0) {
  foreach ($array as $name=>$value) {
     $name = trim($name);
     if (!empty($name)) {
        $object->$name = $this->_arrayToObject($value);
     }
  }
  return $object;
}
else {
  return FALSE;
}

} }

?>

Leave a comment

Please to leave your comment.

Create extension