Oihana PHP System

getDocumentsModel.php

Table of Contents

Functions

getDocumentsModel()  : DocumentsModel|null
Resolves a {@see DocumentsModel} instance from a PSR-11 container or returns a default.

Functions

getDocumentsModel()

Resolves a {@see DocumentsModel} instance from a PSR-11 container or returns a default.

getDocumentsModel([string|DocumentsModel|null $definition = null ][, ContainerInterface|null $container = null ][, DocumentsModel|null $default = null ]) : DocumentsModel|null

This helper function provides a flexible way to obtain a DocumentsModel instance:

  • If $definition is already a DocumentsModel, it is returned as-is.
  • If $definition is a string and $container implements ContainerInterface, the function attempts to resolve the corresponding service from the container.
  • If resolution fails, the provided $default (if any) is returned instead.

This pattern allows for safe dependency resolution in controllers or services, without requiring explicit type-checking or container awareness in user code.

Parameters
$definition : string|DocumentsModel|null = null

The model definition — either:

  • a DocumentsModel instance (returned directly),
  • a string service identifier (resolved from $container),
  • or null (uses $default).
$container : ContainerInterface|null = null

Optional PSR-11 container to resolve string identifiers.

$default : DocumentsModel|null = null

Optional fallback model if no valid instance is found.

Tags
throws
ContainerExceptionInterface

If the container encounters an internal error.

throws
NotFoundExceptionInterface

If $definition is a string not found in the container.

example
use oihana\controllers\helpers\getDocumentsModel;
use oihana\models\interfaces\DocumentsModel;
use Psr\Container\ContainerInterface;

// Case 1: Direct instance
$model = new MyDocumentsModel();
echo getDocumentsModel( $model ) === $model ? 'ok' : 'fail' ; // ok

// Case 2: String identifier resolved via container
$container = new Container(); // implements ContainerInterface
$container->set( 'mainModel', new MyDocumentsModel() );

$resolved = getDocumentsModel( 'mainModel', $container );
echo $resolved instanceof DocumentsModel ? 'ok' : 'fail' ;   // ok

// Case 3: Fallback to default model
$default = new DefaultDocumentsModel();
echo getDocumentsModel( 'unknown', $container, $default ) === $default ? 'ok' : 'fail' ; // ok
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
DocumentsModel|null

The resolved model, the provided default, or null if none.


        
On this page

Search results