Content
Menu Service
Menu Service
Overview
The Menu class is part of the Toolstation\Content\Services\Wordpress\Rest namespace and is used to interact with the WordPress REST API for menu-related operations. It includes methods to retrieve all menus, get a menu by its ID, and get a menu by its slug and language.
Class Definition
Namespace
namespace Toolstation\Content\Services\Wordpress\Rest;
Constants
- PREFIX: A constant that defines the base path for accessing WordPress menu endpoints in the REST API.
public const PREFIX = 'wp-api-menus/v2/menus';
Properties
- $client: An instance of the
RestClientclass used to perform HTTP requests to the WordPress REST API.protected $client;
Constructor
public function __construct(RestClient $client)
- Parameters:
- RestClient $client: The client used to perform REST API requests.
- Description: Initializes the
Menuservice with aRestClientinstance.
Methods
all()
public function all()
- Description: Retrieves all menus from the WordPress REST API. The results are cached to
improve performance. Uses the
Cache::remembermethod to store the menu data for a specified duration, defined by_tsc('content.cache.content'). request to the WordPress REST API endpoint using the slug parameter. If no category is found, it aborts with a 404 error. Returns the first matching category from the response. - Returns: Collection A collection of all menus.
getById($id)
public function getById($id)
- Description: Retrieves a menu based on its ID by making an HTTP GET request to the WordPress REST API endpoint.
- Parameters:
- id (int): The ID of the menu to retrieve.
- Returns: The menu data (array).
getBySlug($slug, $lang)
public function getBySlug($slug, $lang)
- Description: Retrieves a menu based on its slug and language. First attempts to find a menu with the combined slug and language. If not found, attempts to find a menu with just the slug. If neither is found, throws a ContentModuleException with a 404 status code.
- Parameters:
- string $slug: The slug of the menu to retrieve.
- string $lang: The language code to differentiate menus with the same slug but different languages.
- Returns: array-The menu data.
Error Handling
ContentModuleException::contentNotFound($slug, Response::HTTP_NOT_FOUND): Thrown if no menu matching the provided slug and language is found.
Example Usage
$restClient = new RestClient(); // Assuming RestClient is properly instantiated
$menuService = new Menu($restClient);
// Retrieve all menus
$menus = $menuService->all();
// Retrieve a menu by ID
$menu = $menuService->getById(123);
// Retrieve a menu by slug and language
$menu = $menuService->getBySlug('main-menu', 'en');
Notes
- Ensure that the
RestClientclass is properly implemented and configured for making HTTP requests to the WordPress REST API. - The caching mechanism depends on the
Cachefacade and_tscfunction for cache duration. Make sure these are correctly configured in your application.