Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

PHP 7.3+ API Wrapper for The Movie Database

License

NotificationsYou must be signed in to change notification settings

php-tmdb/api

Repository files navigation

LicenseLicenseBuild StatusBuild StatuscodecovPHPTotal Downloads

Tests run with minimal, normal and development dependencies.

Buy me a coffee, or a beer :-)

My stomach will appreciate your donation!

Main features

  • Array implementation of the movie database (RAW)
  • Model implementation of the movie database (By making use of the repositories)
  • AnImageHelper class to help build image urls or html elements.

Attention newcomers to php

If you are new to php and starting a project to learn, I'd recommendyou skip down to the installation,and then followthe quickstart that's just for you!

I do advise you to take a broader look later on what all these PSR standards mean and do for the php community :-).

PSR Compliance

We try to leave as many options open to the end users of this library, as such with 4.0 changes havebeen made to introduce PSR compliance where we can. You bring the dependencies you prefer that are compliantwith PSR standards, register the listeners, and we handle the rest.

Framework implementations

Installation

Installcomposer.

Before we can install the api library, you need to install a set of dependencies that provide the following implementations.

Dependencies you have to fulfill yourself

  • ForPSR-7: HTTP Message Interface, for examplenyholm/psr7.
  • ForPSR-14: Event Dispatcher, for examplesymfony/event-dispatcher.
  • ForPSR-17: HTTP Factories, for examplenyholm/psr7.
  • ForPSR-18: HTTP Client, for exampleguzzlehttp/guzzle.

I urge you to implement the optional caching implementation

When making use of caching, make sure to also includephp-http/cache-plugin in composer, this plugin handles the logic for us,so we don't have to re-invent the wheel. You are however also free to choose to implement your own cache listener, or addthe caching logic inside the http client of your choice.

composer require php-http/cache-plugin:^1.7

Even thoughthemoviedb.org disabledrate limiting since the end of 2019,I'd still recommend enabling the cache to make your application run a bit smoother. As such the427 retry subscriber in previous versions is not present anymore.

  • ForPSR-6: Caching Interface, for examplesymfony/cache.
  • ForPSR-16: Simple Cache, with an PSR-6 adapter for examplesymfony/cache, then usethe PSR-16 to PSR-6 adapter.

Not only will this make your application more responsive, by loading from cache when we can, it also decreases the amount of requests we need to send.

Optional dependencies

  • ForPSR-3: Logger Interface, for examplemonolog/monolog.

Install php-tmdb/api

If the required dependencies above are met, you are ready to install the library.

composer require php-tmdb/api:^4

Include Composer's autoloader:

require_oncedirname(__DIR__).'/vendor/autoload.php';

To use the examples provided, copy theexamples/apikey.php.dist toexamples/apikey.php and change the settings.

New to PSR standards or composer?

If you came here looking to start a fun project to start learning, the above might seem a little daunting.

Don't worry! The documentation here was setup with beginners in mind as well.

We also provide a bunch of examples in theexamples/ folder.

To get started;

composer require php-tmdb/api:^4 symfony/event-dispatcher guzzlehttp/guzzle symfony/cache monolog/monolog nyholm/psr7

Now that we have everything we need installed, let's get started setting up to be able to use the library.

Quick setup

Review the setup files below and go over theexamples folder, for exampleexamples/movies/api/get.php orexamples/movies/api/get.php files.

Constructing the Client

If you have chosen different implementations than the examples suggested beforehand, obviously all the upcoming documentation won't match. Adjust accordingly to your dependencies, we will go along with the examples given earlier.

General API Usage

If you're looking for a simple array entry point the API namespace is the place to be, however we recommend you use therepositories and model's functionality up ahead.

useTmdb\Client;$client =newClient();$movie =$client->getMoviesApi()->getMovie(550);

If you want to provide any other query arguments.

useTmdb\Client;$client =newClient();$movie =$client->getMoviesApi()->getMovie(550, ['language' =>'en']);

For all further calls just review theunit tests orexamples provided, or the API classes themselves.

Model Usage

The library can also be used in an object oriented manner, which I reckon is thepreferred way of doing things.

Instead of calling upon the client, you pass the client onto one of the many repositories and do then some work on it.

useTmdb\Repository\MovieRepository;useTmdb\Client;$client =newClient();$repository =newMovieRepository($client);$movie =$repository->load(87421);echo$movie->getTitle();

The repositories also contain the other API methods that are available through the API namespace.

useTmdb\Repository\MovieRepository;useTmdb\Client;$client =newClient();$repository =newMovieRepository($client);$topRated =$repository->getTopRated(['page' =>3]);// or$popular =$repository->getPopular();

For all further calls just review theunit tests orexamples provided, or the model's themselves.

Event Dispatching

We (can) dispatch the following events inside the library, which by using event listeners you could modify some behavior.

HTTP Client exceptions

  • Tmdb\Event\HttpClientExceptionEvent
    • Allows to still set a successful response if the error can be corrected, by calling$event->isPropagated() in your listener,this does require you to provide a PSR-7 response object and set it with$event->setResponse($response).

TMDB API exceptions

  • Tmdb\Event\TmdbExceptionEvent
    • Allows to still set a successful response if the error can be corrected, by calling$event->isPropagated() in your listener,this does require you to provide a PSR-7 response object and set it with$event->setResponse($response).

Hydration

  • Tmdb\Event\BeforeHydrationEvent,allows modification of the response data before being hydrated.
    • This event will still be thrown regardless if theevent_listener_handles_hydration option is set to false, thisallows for example the logger to still produce records.
  • Tmdb\Event\AfterHydrationEvent,allows modification of the eventual subject returned.

The current implementation within the event dispatcher causes significant overhead, you might actually not want at all.

In the future we will look into this further for improvement, for now we have bigger fish to catch.

From4.0 moving forward by default the hydration events have been disabled.

To re-enable this functionality, we recommend only using it for models you need to modify data for;

useTmdb\Client;$client =newClient(['hydration' => ['event_listener_handles_hydration' =>true,'only_for_specified_models' => [Tmdb\Model\Movie::class        ]    ]]);

If that configuration has been applied, also make sure the event dispatcher you use is aware of ourHydrationListener;

useSymfony\Component\EventDispatcher\EventDispatcher;useTmdb\Event\HydrationEvent;useTmdb\Event\Listener\HydrationListener;$eventDispatcher =newEventDispatcher();$hydrationListener =newHydrationListener($eventDispatcher);$eventDispatcher->addListener(HydrationEvent::class,$hydrationListener);

If you re-enable this functionality without specifying any models, all hydration will be done through the event listeners.

Requests & Responses

  • Tmdb\Event\BeforeRequestEvent
    • Allows modification of the PSR-7 request data before being sent.
    • Allows early response behavior ( think of caching ), by calling$event->isPropagated() in your listener,this does require you to provide a PSR-7 response object and set it with$event->setResponse($response)
  • Tmdb\Event\ResponseEvent
    • Contains theRequest object.
    • Allows modification of the PSR-7 response before being hydrated, this does require you to provide a PSR-7response object and set it with$event->setResponse($response)
    • Allows end-user to implement their own cache, or any other actions you'd like to perform on the given response.

Event listeners

We have a couple of optional event listeners that you could add to provide additional functionality.

Caching

Instead of constructing the defaultRequestListener, construct the client with thePsr6CachedRequestListener.

useSymfony\Component\Cache\Adapter\FilesystemAdapter;useTmdb\Event\Listener\Psr6CachedRequestListener;useTmdb\Repository\MovieRepository;useTmdb\Client;$client =newClient();$cache =newFilesystemAdapter('php-tmdb',86400,__DIR__ .'/cache');$requestListener =newPsr6CachedRequestListener($client->getHttpClient(),$client->getEventDispatcher(),$cache,$client->getHttpClient()->getPsr17StreamFactory(),    []);$repository =newMovieRepository($client);$popular =$repository->getPopular();

The current implementation will change again in the future, it will either involve a small change in listener registration,or will just happen without you being aware. We currently base this onphp-http/cache-plugin, which pulls in extradependencies we don't really use. Since caching is quite a subject itself, for now we have chosen the "quick 'n dirty way".

Logging

The logging is divided in a couple of listeners, so you can decide what you want to log, or not. All of theselisteners have support for writing custom formatted messages. See the relevant interfaces and classes located in theTmdb\Formatter namespace.

Instead of monolog you can pass any PSR-3 compatible logger.

Tmdb\Event\Listener\Logger\LogApiErrorListener

useMonolog\Logger;useSymfony\Component\EventDispatcher\EventDispatcher;useTmdb\Event\Listener\Logger\LogApiErrorListener;useTmdb\Event\TmdbExceptionEvent;useTmdb\Formatter\TmdbApiException\SimpleTmdbApiExceptionFormatter;$eventDispatcher =newEventDispatcher();$apiErrorListener =newLogApiErrorListener(newLogger(),newSimpleTmdbApiExceptionFormatter());$eventDispatcher->addListener(TmdbExceptionEvent::class,$apiErrorListener);

This will log exceptions thrown when a response has successfully been received, but the response indicated the request was not successful.

[2021-01-01 13:24:14] php-tmdb.CRITICAL: Critical API exception: 7 Invalid API key: You must be granted a valid key. [] []

Tmdb\Event\Listener\Logger\LogHttpMessageListener

useSymfony\Component\EventDispatcher\EventDispatcher;useTmdb\Event\BeforeRequestEvent;useTmdb\Event\HttpClientExceptionEvent;useTmdb\Event\Listener\Logger\LogHttpMessageListener;useTmdb\Event\ResponseEvent;useTmdb\Formatter\HttpMessage\SimpleHttpMessageFormatter;$eventDispatcher =newEventDispatcher();$requestLoggerListener =newLogHttpMessageListener(newMonolog\Logger(),newSimpleHttpMessageFormatter());$eventDispatcher->addListener(BeforeRequestEvent::class,$requestLoggerListener);$eventDispatcher->addListener(ResponseEvent::class,$requestLoggerListener);$eventDispatcher->addListener(HttpClientExceptionEvent::class,$requestLoggerListener);

This will log outgoing requests and responses.

[2021-01-01 13:11:18] php-tmdb.INFO: Sending request: GET https://api.themoviedb.org/3/company/1?include_adult=true&language=en-US&region=us 1.1 {"length":0,"has_session_token":false} [][2021-01-01 13:11:18] php-tmdb.INFO: Received response: 200 OK 1.1 {"status_code":200,"length":223} []

In case of any other PSR-18 client exceptions ( connection errors for example ), these will also be written to the log.

[2021-01-01 13:36:39] php-tmdb.INFO: Sending request: GET https://api.themoviedb.org/3/company/1?include_adult=true&language=en-US&region=us 1.1 {"length":0,"has_session_token":false} [][2021-01-01 13:36:39] php-tmdb.CRITICAL: Critical http client error: 0 cURL error 7: Failed to connect to api.themoviedb.org port 443: Connection refused (see https://curl.haxx.se/libcurl/c/libcurl-errors.html) {"request":"https://api.themoviedb.org/3/company/1?include_adult=true&language=en-US&region=us"} []

Tmdb\Event\Listener\Logger\LogHydrationListener

useSymfony\Component\EventDispatcher\EventDispatcher;useTmdb\Event\BeforeHydrationEvent;useTmdb\Event\Listener\Logger\LogHydrationListener;useTmdb\Formatter\Hydration\SimpleHydrationFormatter;$eventDispatcher =newEventDispatcher();$hydrationLoggerListener =newLogHydrationListener(newMonolog\Logger(),newSimpleHydrationFormatter(),false// set to true if you wish to add the json data passed for each hydration, do not use this in production!);$eventDispatcher->addListener(BeforeHydrationEvent::class,$hydrationLoggerListener);

This will log hydration of models with (optionally) their data, useful for debugging.

[2021-01-01 13:11:18] php-tmdb.DEBUG: Hydrating model "Tmdb\Model\Image\LogoImage". {"data":{"file_path":"/o86DbpburjxrqAzEDhXZcyE8pDb.png"},"data_size":49} [][2021-01-01 13:11:18] php-tmdb.DEBUG: Hydrating model "Tmdb\Model\Company". {"data":{"description":"","headquarters":"San Francisco, California","homepage":"https://www.lucasfilm.com/","id":1,"logo_path":"/o86DbpburjxrqAzEDhXZcyE8pDb.png","name":"Lucasfilm Ltd.","origin_country":"US","parent_company":null},"data_size":227} []

For calls with a lot of appended data, this quickly becomes a large dump in the log file, and I would advise toonly use this when necessary.

Do not enable the hydration data dumping on production, it will generate massive logs.

Adult filter

To enable inclusion of results considered "adult", add the following listener.

useSymfony\Component\EventDispatcher\EventDispatcher;useTmdb\Event\BeforeRequestEvent;useTmdb\Event\Listener\Request\AdultFilterRequestListener;$eventDispatcher =newEventDispatcher();$adultFilterListener =newAdultFilterRequestListener(true);$eventDispatcher->addListener(BeforeRequestEvent::class,$adultFilterListener);

Language filter

To enable filtering contents on language, add the following listener.

useSymfony\Component\EventDispatcher\EventDispatcher;useTmdb\Event\BeforeRequestEvent;useTmdb\Event\Listener\Request\LanguageFilterRequestListener;$eventDispatcher =newEventDispatcher();$languageFilterListener =newLanguageFilterRequestListener('nl-NL');$eventDispatcher->addListener(BeforeRequestEvent::class,$languageFilterListener);

Region filter

To enable filtering contents on region, add the following listener.

useSymfony\Component\EventDispatcher\EventDispatcher;useTmdb\Event\BeforeRequestEvent;useTmdb\Event\Listener\Request\RegionFilterRequestListener;$eventDispatcher =newEventDispatcher();$regionFilterListener =newRegionFilterRequestListener('nl');$eventDispatcher->addListener(BeforeRequestEvent::class,$regionFilterListener);

Guest session

If you want to make use of guest sessions, you need to specify this explicitly on the client.

useTmdb\Client;useTmdb\Token\Session\GuestSessionToken;$client =newClient();$client->setGuestSessionToken(newGuestSessionToken('my_token'));// Now you can make calls in the guest sessions namespace.

Image Helper

AnImageHelper class is present to take care of the images, which does require the configuration to be loaded:

useTmdb\Client;useTmdb\Helper\ImageHelper;useTmdb\Model\Image;useTmdb\Repository\ConfigurationRepository;$client =newClient();$image =newImage();$configRepository =newConfigurationRepository($client);$config =$configRepository->load();$imageHelper =newImageHelper($config);echo$imageHelper->getHtml($image,'w154',154,80);

Collection Filtering

We also provide some easy methods to filter any collection, you should note however you can always implement your own filter easily by using Closures:

useTmdb\Model\Movie;useTmdb\Model\Image\PosterImage;$movie =newMovie();foreach($movie->getImages()->filter(function($key,$value){return$valueinstanceof PosterImage;        }    )as$image) {// do something with all poster images}

These basic filters however are already covered in theImages collection object:

useTmdb\Model\Movie;/** @var $movie Movie **/$backdrop =$movie    ->getImages()    ->filterBackdrops();

And there are more Collections which provide filters, but you will find those out along the way.

The GenericCollection and the ResultCollection

  • TheGenericCollection holds any collection of objects (e.g. an collection of movies).
  • TheResultCollection is an extension of theGenericCollection, and inherits the response parameters(page, total_pages, total_results) from an result set, this can be used to create pagination.

[8]ページ先頭

©2009-2025 Movatter.jp