Custom PHP

How I Architect a PHP Streaming Catalogue for Web and Android TV

PHP streaming catalogue architecture is a set of boring decisions that keep browsing fast and playback resilient: a normalised title model, cached hero and shelf queries, idempotent watchlist writes, and a player that falls back from HLS to progressive MP4. I build it with PDO and explicit HTTP caching, then expose the same data to an Android TV Leanback layout driven by DPAD focus.

By Saif Al Jahanwebdev-saif.com

Start with the content model, not the screens

A streaming catalogue is mostly a content problem wearing a UI costume. In a SAIF FLIX-style build I model titles as one table with id, slug, type (film or series), year, runtime, rating, poster_path, backdrop_path and a status flag, then keep episodes in a child table keyed by title_id and season_number. Genres and cast are separate lookup tables joined through title_genre and title_person, because a title can belong to several genres and a genre to thousands of titles. Every query goes through PDO prepared statements; no user input is interpolated into SQL. Assets sit behind one asset_url() helper, so moving from local storage to object storage changes a single function rather than twelve templates. I keep denormalised popularity and hero_weight columns on titles purely to keep shelf queries free of joins.

  • titles: id, slug, type, year, runtime, rating, status, popularity, hero_weight
  • episodes: title_id, season_number, episode_number, runtime, source_id
  • assets: id, title_id, kind, path, mime, width, height
  • title_genre and title_person join tables with composite primary keys

Rotating heroes without ORDER BY RAND()

The hero is the highest-visibility surface on the page, so I never pick one with ORDER BY RAND(); it forces a full sort of the catalogue on every request and makes the LCP image unpredictable. Instead I keep a hero_slots table with title_id, weight, starts_at and ends_at, then select from the active rows using a stable daily seed cached in APCu. The seed changes once per day, so all visitors see the same five titles on a given day and the browser can reuse the cached backdrop. I reserve the hero box at a fixed 21:9 aspect ratio, output the first image with fetchpriority="high" and the rest with loading="lazy", and cache the fragment with Cache-Control: public, max-age=300. Changing the hero must never push the shelf below it down the page — that is a CLS bug, not a design choice.

  • Stable daily seed in APCu instead of per-request randomness
  • Weighted hero_slots rows with explicit start and end windows
  • Fixed 21:9 hero box reserved in CSS before images arrive
  • fetchpriority="high" on the first backdrop only

Filtered shelves that stay cheap at page 50

Shelves are filtered queries with good indexes. I expose filters as plain query parameters such as ?genre=action&year=2024&sort=popular&page=2 and map each one to a whitelisted column and direction in PHP, so a visitor cannot inject an arbitrary ORDER BY. The common path across genre_id, year and status gets a composite index, and I switch to keyset pagination on (popularity, id) rather than deep OFFSET once a shelf passes a few hundred items. Shelf HTML is cached per filter signature with stale-while-revalidate, while the count for the pagination bar is cached separately because it changes less often. I cap page size at 24 and return 404 for out-of-range pages. Nothing here needs a search cluster: a well-indexed MySQL table and a small PHP router are enough for a catalogue in the tens of thousands of titles.

  • Whitelist sort columns and directions; never concatenate request values into SQL
  • Composite index on (genre_id, year, status, popularity, id)
  • Keyset pagination after roughly page 10 to avoid deep OFFSET scans
  • Cache key derived from the canonical filter signature
  • Hard cap of 24 items per shelf page

Watchlists: idempotent writes and guest merge

A watchlist is a small feature that breaks in predictable ways: double clicks create duplicate rows, and guest state disappears at login. I store watchlist(user_id, title_id, created_at) with a unique key on (user_id, title_id) and make the toggle endpoint idempotent — POST /watchlist/toggle returns the current state instead of blindly inserting. For signed-out visitors I keep a short-lived signed cookie holding title IDs with an HMAC, merge it into the database on login, then clear the cookie. The button uses aria-pressed and updates optimistically, with a rollback if the request fails. Every write checks a CSRF token tied to the session. I do not store playback progress in the same table; progress belongs in a separate progress record keyed by user and episode, with its own write frequency.

  • Unique (user_id, title_id) key prevents duplicate entries
  • HMAC-signed guest cookie merged into the database at login
  • CSRF token checked on every toggle request
  • aria-pressed state with optimistic UI and rollback on failure
  • Playback progress stored separately from the watchlist

Playback fallbacks that recover on a real device

Playback is where catalogue sites lose trust. My primary source is HLS: a .m3u8 master playlist with Cache-Control: no-cache, segmented media served with Accept-Ranges: bytes, and CORS headers on segment responses when the player runs on a different origin. In the browser I use hls.js where MediaSource is supported and native HLS on Safari via video.canPlayType("application/vnd.apple.mpegurl"). I listen to Hls.Events.ERROR, retry network errors a bounded number of times with backoff, attempt hls.recoverMediaError() on media errors, and after two fatal failures swap the video source to a progressive MP4 stored under the same assets row. The fallback is visible, not hidden: a small low-bandwidth control lets a viewer choose it manually. If neither source loads, I show a poster, a plain-language error and a reload action instead of an endless spinner.

  • Master .m3u8 plus a progressive MP4 per title in the assets table
  • Bounded retries with backoff on fatal Hls.Events.ERROR network errors
  • recoverMediaError() before giving up on the HLS instance
  • CORS and Accept-Ranges headers verified on segment responses
  • Final error state with poster and reload, never an infinite spinner

One catalogue API for web and Android TV

The Leanback app should not scrape the website. I expose a small JSON endpoint, for example GET /api/v1/catalogue?rows=hero,trending,continue&limit=12, that returns rows of cards with id, title, poster, backdrop, duration and a play_url. The same PHP repository methods that build the web shelves build this response, so ranking rules do not drift between surfaces. Responses carry Cache-Control: public, max-age=120 and an ETag derived from the newest updated_at among the titles in those rows; a conditional If-None-Match request returns 304 and costs almost nothing. I version the path and keep field names stable, because TV apps are updated far less often than a website and an old client must keep working after a server deploy.

Leanback layout: focus is the design system

On Android TV the remote, not the mouse, is the input. I use the Leanback BrowseSupportFragment with ArrayObjectAdapter and ListRow objects, each row built from the API response and rendered by a CardPresenter with an ImageCardView. Focus is the primary state: I apply a scale and elevation change on focus, keep a visible outline, and set nextFocusLeft, nextFocusRight, nextFocusUp and nextFocusDown explicitly where a row wraps, because the default Leanback focus search can jump to an unexpected card. Backdrops are 16:9 at 1280x720, text stays at or above 14sp, and I leave roughly 5% overscan-safe margin so nothing is clipped on older sets. DPAD centre and BACK are handled by the fragment; a long-press on a card opens details instead of starting playback immediately.

  • BrowseSupportFragment with ArrayObjectAdapter and one ListRow per shelf
  • ImageCardView with focus scale, outline and explicit nextFocus IDs
  • 1280x720 backdrops, 14sp or larger text, roughly 5% overscan margin
  • DPAD centre plays; long-press opens the DetailsSupportFragment
  • ExoPlayer with MediaSessionCompat for playback and lock-screen control

Frequently asked questions

What does PHP streaming catalogue architecture include?

It includes four layers: a normalised title and asset model in MySQL, a query and caching layer that builds heroes and shelves, a write layer for watchlists and progress, and a playback layer that can fall back from HLS to a progressive MP4. The Android TV app consumes the same data through a versioned JSON endpoint rather than scraping rendered HTML.

Why avoid ORDER BY RAND() for rotating heroes?

Because it sorts the whole candidate set on every request, making response time unpredictable and changing the LCP image on each page view. I use a daily seed stored in APCu and a hero_slots table with weights and time windows. Every visitor gets the same five titles that day, the browser reuses the cached backdrop, and layout stays stable.

How do you handle playback when HLS fails?

I retry network errors a bounded number of times with backoff, call recoverMediaError() for media errors, and after two fatal failures swap the video source to a progressive MP4 stored under the same assets row. A manual low-bandwidth control is available, and a final error state shows the poster with a reload action instead of an endless spinner.

Can the same PHP backend serve web and Android TV?

Yes. I keep catalogue queries in repository methods and use them for both the HTML shelves and a versioned JSON endpoint. The TV app requests rows such as hero, trending and continue-watching, each card carrying title, images and a play URL. An ETag based on the newest title update lets unchanged responses return 304, which keeps a TV client cheap to refresh.

What is the biggest mistake in a Leanback layout?

Treating it as a narrow website. Leanback is built around DPAD focus, so the important work is focus order, visible focus states and overscan-safe sizing, not just responsive CSS. I set explicit next-focus IDs where rows wrap, keep text above 14sp, leave about 5% margin, and reserve long-press for details instead of immediate playback.

Written by Saif Al Jahan, webdev-saif.com · Mymensingh, Bangladesh. Last updated .