Skip to content

Base Manager

The Base Manager in WNCMS (named ModelManager) is an abstract service class that handles model data fetching, filtering, and caching in a standardized way. All specific managers like PostManager, LinkManager, or custom package managers extend this class to reuse its query and caching logic.


Purpose

Managers serve as a middle layer between controllers and models. They centralize data access, apply query filters, handle caching, and prepare paginated or collection-based results. This allows developers to keep controllers thin and consistent.


Base Class

php
namespace Wncms\Services\Managers;

abstract class ModelManager

Every manager must extend ModelManager and implement these required methods:

  • getModelClass(): string — return the model class handled by the manager.
  • buildListQuery(array $options): mixed — define how to query a list of models.

Example Structure

php
class PostManager extends ModelManager
{
    protected string $cacheKeyPrefix = 'wncms_post';
    protected string|array $cacheTags = ['posts'];
    protected bool $shouldAuth = false;

    public function getModelClass(): string
    {
        return wncms()->getModelClass('post');
    }

    protected function buildListQuery(array $options): mixed
    {
        $q = $this->query()->where('status', 'published');
        $this->applyOrdering($q, 'created_at');
        return $q;
    }
}

Key Responsibilities

Data Retrieval

get(array $options = []): ?Model

Fetch a single model record using any of these identifiers:

OptionTypeDescription
idintModel ID
slugstringSlug field
namestringName field
withsarrayRelations to eager-load
wheresarrayExtra where conditions
cacheboolEnable cache (default: true)

This method returns a single Model instance or null.


Data Listing

getList(array $options = []): Collection|Paginator

Get a filtered list of models with optional pagination or caching.

Common options include:

OptionTypeDescription
page_sizeintNumber of items per page
pageintCurrent page number
orderstringOrder column
sequencestringasc / desc
tagsarray / stringFilter by tag name or ID
excluded_tag_idsarray / stringExclude tag IDs
keywordsarray / stringKeyword search
countintLimit count
is_randomboolRandomize order
cacheboolUse cache

Counting

getCount(array $options = []): int

Count models matching filters.


Filtering Helpers

These methods help apply query conditions consistently:

MethodDescription
applyTagFilter()Include models with certain tags
applyExcludedTags()Exclude models with certain tag IDs
applyKeywordFilter()Search across multiple columns
applyIds()Filter by IDs
applyExcludeIds()Exclude IDs
applyStatus()Filter by a status column
applyWebsiteId()Scope by website in multi-site mode
applyWiths()Apply eager loading
applyOrdering()Apply order or random order
applySelect()Limit selected columns
applyOffset()Apply offset
applyLimit()Limit result count

Query Lifecycle

  1. buildListQuery() — create the base query.
  2. finalizeResult() — handle pagination, count limit, and get results.

Caching Support

  • WNCMS cache system is integrated with tag-based invalidation.
  • Controlled by settings enable_cache and data_cache_time.
MethodPurpose
getCacheKeyPrefix()Returns cache key prefix
getCacheTag()Returns cache tag(s) for invalidation
getCacheKey()Build unique cache key per query
getCacheTime()Retrieve cache duration
run()Run arbitrary function with caching support

Website and Multi-site Support

applyWebsiteId() automatically scopes the query when multi_website is enabled or when the model supports website filtering through applyWebsiteScope().


Tag Support

getAllowedTagTypes(): array

Fetches allowed tag types from the model and formats them for frontend display.

Returns structured array:

php
[
  [
    'full'  => 'post_category',
    'key'   => 'category',
    'label' => __('wncms::word.post_category'),
  ],
]

Extending ModelManager

To build your own manager:

  1. Create a class under app/Services/Managers/.
  2. Extend ModelManager.
  3. Implement getModelClass() and buildListQuery().
  4. Use helper methods like applyTagFilter(), applyKeywordFilter(), and applyOrdering().

Common Use Cases

  • Filter and paginate models for frontend lists.
  • Cache complex queries for speed.
  • Apply global multi-site or tag filters.
  • Expose consistent query results to API controllers.

Built with ❤️ for WNCMS