Skip to content

Phalcon mvc

NOTE

All classes are prefixed with Phalcon

Mvc\Application

Class Source on GitHub

Phalcon\Mvc\Application

This component encapsulates all the complex operations behind instantiating every component needed and integrating it with the rest to allow the MVC pattern to operate as desired.

use Phalcon\Mvc\Application;

class MyApp extends Application
{
    /**
     * Register the services here to make them general or register
     * in the ModuleDefinition to make them module-specific
     *\/
    protected function registerServices()
    {

    }

    /**
     * This method registers all the modules in the application
     *\/
    public function main()
    {
        $this->registerModules(
            [
                "frontend" => [
                    "className" => "Multiple\\Frontend\\Module",
                    "path"      => "../apps/frontend/Module.php",
                ],
                "backend" => [
                    "className" => "Multiple\\Backend\\Module",
                    "path"      => "../apps/backend/Module.php",
                ],
            ]
        );
    }
}

$application = new MyApp();

$application->main();

Uses Closure · Phalcon\Application\AbstractApplication · Phalcon\Di\DiInterface · Phalcon\Events\ManagerInterface · Phalcon\Http\ResponseInterface · Phalcon\Mvc\Application\Exception · Phalcon\Mvc\Application\Exceptions\ContainerRequired · Phalcon\Mvc\Application\Exceptions\InvalidModuleDefinition · Phalcon\Mvc\Application\Exceptions\ModuleDefinitionPathNotFound · Phalcon\Mvc\ModuleDefinitionInterface · Phalcon\Mvc\Router\RouteInterface

Method Summary

Properties

protected bool $implicitView = true
protected bool $sendCookies = true
protected bool $sendHeaders = true

Methods

Public · 4

handle()

public function handle( string $uri ): ResponseInterface|bool;

Handles a MVC request

sendCookiesOnHandleRequest()

public function sendCookiesOnHandleRequest( bool $sendCookies ): static;

Enables or disables sending cookies by each request handling

sendHeadersOnHandleRequest()

public function sendHeadersOnHandleRequest( bool $sendHeaders ): static;

Enables or disables sending headers by each request handling

useImplicitView()

public function useImplicitView( bool $implicitView ): static;

By default. The view is implicitly buffering all the output You can full disable the view component using this method

Mvc\Application\Exception

Class Source on GitHub

Phalcon\Mvc\Application\Exception

Exceptions thrown in Phalcon\Mvc\Application class will use this class

Mvc\Application\Exceptions\ContainerRequired

Class Source on GitHub

Uses Phalcon\Mvc\Application\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Application\Exceptions\InvalidModuleDefinition

Class Source on GitHub

Uses Phalcon\Mvc\Application\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name = null,
    string $reason = null
);

Mvc\Application\Exceptions\ModuleDefinitionPathNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Application\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $path );

Mvc\Controller

Abstract Source on GitHub

Phalcon\Mvc\Controller

Every application controller should extend this class that encapsulates all the controller functionality

The controllers provide the “flow” between models and views. Controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.

<?php

class PeopleController extends \Phalcon\Mvc\Controller
{
    // This action will be executed by default
    public function indexAction()
    {

    }

    public function findAction()
    {

    }

    public function saveAction()
    {
        // Forwards flow to the index action
        return $this->dispatcher->forward(
            [
                "controller" => "people",
                "action"     => "index",
            ]
        );
    }
}

Uses Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface

Method Summary

Methods

Public · 3

__construct()

final public function __construct();

Phalcon\Mvc\Controller constructor

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

setEventsManager()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

Protected · 1

fireManagerEvent()

protected function fireManagerEvent(
    string $eventName,
    mixed $data = null,
    bool $cancellable = true
): mixed|bool;

Helper method to fire an event

Mvc\ControllerInterface

Interface Source on GitHub

Phalcon\Mvc\ControllerInterface

Interface for controller handlers

  • Phalcon\Mvc\ControllerInterface

Mvc\Controller\BindModelInterface

Interface Source on GitHub

Phalcon\Mvc\Controller\BindModelInterface

Interface for Phalcon\Mvc\Controller

  • Phalcon\Mvc\Controller\BindModelInterface

Method Summary

Methods

Public · 1

getModelName()

public static function getModelName(): string;

Return the model name associated with this controller

Mvc\Dispatcher

Class Source on GitHub

Dispatching is the process of taking the request object, extracting the module name, controller name, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller.

$di = new \Phalcon\Di\Di();

$dispatcher = new \Phalcon\Mvc\Dispatcher();

$dispatcher->setDI($di);

$dispatcher->setControllerName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);

$controller = $dispatcher->dispatch();

Uses Phalcon\Dispatcher\AbstractDispatcher · Phalcon\Events\ManagerInterface · Phalcon\Http\ResponseInterface · Phalcon\Mvc\Dispatcher\Exception · Phalcon\Mvc\Dispatcher\Exceptions\ResponseServiceUnavailable

Method Summary

Properties

protected string $defaultAction = "index"
protected string $defaultHandler = "index"
protected string $handlerSuffix = "Controller"

Methods

Public · 9

forward()

public function forward( array $forward ): void;

Forwards the execution flow to another controller/action.

use Phalcon\Events\Event;
use Phalcon\Mvc\Dispatcher;
use App\Backend\Bootstrap as Backend;
use App\Frontend\Bootstrap as Frontend;

// Registering modules
$modules = [
    "frontend" => [
        "className" => Frontend::class,
        "path"      => __DIR__ . "/app/Modules/Frontend/Bootstrap.php",
        "metadata"  => [
            "controllersNamespace" => "App\Frontend\Controllers",
        ],
    ],
    "backend" => [
        "className" => Backend::class,
        "path"      => __DIR__ . "/app/Modules/Backend/Bootstrap.php",
        "metadata"  => [
            "controllersNamespace" => "App\Backend\Controllers",
        ],
    ],
];

$application->registerModules($modules);

// Setting beforeForward listener
$eventsManager  = $di->getShared("eventsManager");

$eventsManager->attach(
    "dispatch:beforeForward",
    function(Event $event, Dispatcher $dispatcher, array $forward) use ($modules) {
        $metadata = $modules[$forward["module"]]["metadata"];

        $dispatcher->setModuleName(
            $forward["module"]
        );

        $dispatcher->setNamespaceName(
            $metadata["controllersNamespace"]
        );
    }
);

// Forward
$this->dispatcher->forward(
    [
        "module"     => "backend",
        "controller" => "posts",
        "action"     => "index",
    ]
);

getActiveController()

public function getActiveController(): ControllerInterface;

Returns the active controller in the dispatcher

getControllerClass()

public function getControllerClass(): string;

Possible controller class name that will be located to dispatch the request

getControllerName()

public function getControllerName(): string;

Gets last dispatched controller name

getLastController()

public function getLastController(): ControllerInterface;

Returns the latest dispatched controller

getPreviousControllerName()

public function getPreviousControllerName(): string;

Gets previous dispatched controller name

Note: This is an Mvc-specific alias for the base getPreviousHandlerName().

setControllerName()

public function setControllerName( string $controllerName ): DispatcherInterface;

Sets the controller name to be dispatched

setControllerSuffix()

public function setControllerSuffix( string $controllerSuffix ): DispatcherInterface;

Sets the default controller suffix

setDefaultController()

public function setDefaultController( string $controllerName ): DispatcherInterface;

Sets the default controller name

Protected · 2

handleException()

protected function handleException( \Exception $exception );

Handles a user exception

throwDispatchException()

protected function throwDispatchException(
    string $message,
    int $exceptionCode = 0
);

Throws an internal exception

Mvc\DispatcherInterface

Interface Source on GitHub

Phalcon\Mvc\DispatcherInterface

Interface for Phalcon\Mvc\Dispatcher

Uses Phalcon\Contracts\Mvc\Dispatcher

Mvc\Dispatcher\Exception

Class Source on GitHub

Phalcon\Mvc\Dispatcher\Exception

Exceptions thrown in Phalcon\Mvc\Dispatcher will use this class

Mvc\Dispatcher\Exceptions\ResponseServiceUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\Dispatcher\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\EntityInterface

Interface Source on GitHub

Phalcon\Mvc\EntityInterface

Interface for Phalcon\Mvc\Collection and Phalcon\Mvc\Model

  • Phalcon\Mvc\EntityInterface

Method Summary

Methods

Public · 2

readAttribute()

public function readAttribute( string $attribute ): mixed|null;

Reads an attribute value by its name

writeAttribute()

public function writeAttribute(
    string $attribute,
    mixed $value
);

Writes an attribute value by its name

Mvc\Micro

Class Source on GitHub

Phalcon\Mvc\Micro

With Phalcon you can create "Micro-Framework like" applications. By doing this, you only need to write a minimal amount of code to create a PHP application. Micro applications are suitable to small applications, APIs and prototypes in a practical way.

$app = new \Phalcon\Mvc\Micro();

$app->get(
    "/say/welcome/{name}",
    function ($name) {
        echo "<h1>Welcome $name!</h1>";
    }
);

$app->handle("/say/welcome/Phalcon");

Uses ArrayAccess · Closure · Phalcon\Cache\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Di\FactoryDefault · Phalcon\Di\Injectable · Phalcon\Di\ServiceInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Http\ResponseInterface · Phalcon\Mvc\Micro\Collection · Phalcon\Mvc\Micro\CollectionInterface · Phalcon\Mvc\Micro\Exception · Phalcon\Mvc\Micro\Exceptions\ContainerRequired · Phalcon\Mvc\Micro\Exceptions\ErrorHandlerNotCallable · Phalcon\Mvc\Micro\Exceptions\HandlerNotCallable · Phalcon\Mvc\Micro\Exceptions\InvalidRegisteredHandler · Phalcon\Mvc\Micro\Exceptions\MissingCollectionMainHandler · Phalcon\Mvc\Micro\Exceptions\NoHandlersToMount · Phalcon\Mvc\Micro\Exceptions\NoMatchedRouteHandler · Phalcon\Mvc\Micro\Exceptions\NotFoundHandlerNotCallable · Phalcon\Mvc\Micro\Exceptions\ResponseHandlerNotCallable · Phalcon\Mvc\Micro\LazyLoader · Phalcon\Mvc\Micro\MiddlewareInterface · Phalcon\Mvc\Model\BinderInterface · Phalcon\Mvc\Router\RouteInterface · Throwable

Method Summary

public __construct( DiInterface $container = null ) Phalcon\Mvc\Micro constructor public static after( mixed $handler ) Appends an 'after' middleware to be called after execute the route public static afterBinding( mixed $handler ) Appends a afterBinding middleware to be called after model binding public static before( mixed $handler ) Appends a before middleware to be called before execute the route public RouteInterface delete(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is DELETE public static error( mixed $handler ) Sets a handler that will be called when an exception is thrown handling public static finish( mixed $handler ) Appends a 'finish' middleware to be called when the request is finished public RouteInterface get(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is GET public getActiveHandler() Return the handler that will be called for the matched route public array getBoundModels() Returns bound models from binder instance public ManagerInterface|null getEventsManager() Returns the internal event manager public array getHandlers() Returns the internal handlers attached to the application public BinderInterface|null getModelBinder() Gets model binder public getReturnedValue() Returns the value returned by the executed handler public RouterInterface getRouter() Returns the internal router used by the application public getService( string $serviceName ) Obtains a service from the DI public getSharedService( string $serviceName ) Obtains a shared service from the DI public handle( string $uri ) Handle the whole request public bool hasService( string $serviceName ) Checks if a service is registered in the DI public RouteInterface head(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is HEAD public RouteInterface map(string $routePattern,mixed $handler) Maps a route to a handler without any HTTP method constraint public static mount( CollectionInterface $collection ) Mounts a collection of handlers public static notFound( mixed $handler ) Sets a handler that will be called when the router does not match any of public bool offsetExists( mixed $offset ) Check if a service is registered in the internal services container using public mixed offsetGet( mixed $offset ) Allows to obtain a shared service in the internal services container public void offsetSet(mixed $offset,mixed $value) Allows to register a shared service in the internal services container public void offsetUnset( mixed $offset ) Removes a service from the internal services container using the array public RouteInterface options(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is OPTIONS public RouteInterface patch(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is PATCH public RouteInterface post(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is POST public RouteInterface put(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is PUT public self setActiveHandler( mixed $activeHandler ) Sets externally the handler that must be called by the matched route public void setDI( DiInterface $container ) Sets the DependencyInjector container public void setEventsManager( ManagerInterface $eventsManager ) Sets the events manager public static setModelBinder(BinderInterface $modelBinder,mixed $cache = null) Sets model binder public static setResponseHandler( mixed $handler ) Appends a custom 'response' handler to be called instead of the default public ServiceInterface setService(string $serviceName,mixed $definition,bool $isShared = false) Sets a service from the DI public void stop() Stops the middleware execution avoiding than other middlewares be

Properties

protected callable|null $activeHandler = null
protected array $afterBindingHandlers = []
protected array $afterHandlers = []
protected array $beforeHandlers = []
protected DiInterface|null $container = null
protected callable|null $errorHandler = null
protected ManagerInterface|null $eventsManager = null
protected array $finishHandlers = []
protected array $handlers = []
protected BinderInterface|null $modelBinder = null
protected callable|null $notFoundHandler = null
protected callable|null $responseHandler = null
protected mixed|null $returnedValue = null
protected RouterInterface|null $router = null
protected bool $stopped = false

Methods

Public · 38

__construct()

public function __construct( DiInterface $container = null );

Phalcon\Mvc\Micro constructor

after()

public function after( mixed $handler ): static;

Appends an 'after' middleware to be called after execute the route

afterBinding()

public function afterBinding( mixed $handler ): static;

Appends a afterBinding middleware to be called after model binding

before()

public function before( mixed $handler ): static;

Appends a before middleware to be called before execute the route

delete()

public function delete(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler that only matches if the HTTP method is DELETE

error()

public function error( mixed $handler ): static;

Sets a handler that will be called when an exception is thrown handling the route

finish()

public function finish( mixed $handler ): static;

Appends a 'finish' middleware to be called when the request is finished

get()

public function get(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler that only matches if the HTTP method is GET

getActiveHandler()

public function getActiveHandler();

Return the handler that will be called for the matched route

getBoundModels()

public function getBoundModels(): array;

Returns bound models from binder instance

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

getHandlers()

public function getHandlers(): array;

Returns the internal handlers attached to the application

getModelBinder()

public function getModelBinder(): BinderInterface|null;

Gets model binder

getReturnedValue()

public function getReturnedValue();

Returns the value returned by the executed handler

getRouter()

public function getRouter(): RouterInterface;

Returns the internal router used by the application

getService()

public function getService( string $serviceName );

Obtains a service from the DI

getSharedService()

public function getSharedService( string $serviceName );

Obtains a shared service from the DI

handle()

public function handle( string $uri );

Handle the whole request

hasService()

public function hasService( string $serviceName ): bool;

Checks if a service is registered in the DI

head()

public function head(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler that only matches if the HTTP method is HEAD

map()

public function map(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler without any HTTP method constraint

mount()

public function mount( CollectionInterface $collection ): static;

Mounts a collection of handlers

notFound()

public function notFound( mixed $handler ): static;

Sets a handler that will be called when the router does not match any of the defined routes

offsetExists()

public function offsetExists( mixed $offset ): bool;

Check if a service is registered in the internal services container using the array syntax

offsetGet()

public function offsetGet( mixed $offset ): mixed;

Allows to obtain a shared service in the internal services container using the array syntax

var_dump(
    $app["request"]
);

offsetSet()

public function offsetSet(
    mixed $offset,
    mixed $value
): void;

Allows to register a shared service in the internal services container using the array syntax

   $app["request"] = new \Phalcon\Http\Request();

offsetUnset()

public function offsetUnset( mixed $offset ): void;

Removes a service from the internal services container using the array syntax

options()

public function options(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler that only matches if the HTTP method is OPTIONS

patch()

public function patch(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler that only matches if the HTTP method is PATCH

post()

public function post(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler that only matches if the HTTP method is POST

put()

public function put(
    string $routePattern,
    mixed $handler
): RouteInterface;

Maps a route to a handler that only matches if the HTTP method is PUT

setActiveHandler()

public function setActiveHandler( mixed $activeHandler ): self;

Sets externally the handler that must be called by the matched route

setDI()

public function setDI( DiInterface $container ): void;

Sets the DependencyInjector container

setEventsManager()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

setModelBinder()

public function setModelBinder(
    BinderInterface $modelBinder,
    mixed $cache = null
): static;

Sets model binder

$micro = new Micro($di);

$micro->setModelBinder(
    new Binder(),
    'cache'
);

setResponseHandler()

public function setResponseHandler( mixed $handler ): static;

Appends a custom 'response' handler to be called instead of the default response handler

setService()

public function setService(
    string $serviceName,
    mixed $definition,
    bool $isShared = false
): ServiceInterface;

Sets a service from the DI

stop()

public function stop(): void;

Stops the middleware execution avoiding than other middlewares be executed

Mvc\Micro\Collection

Class Source on GitHub

Phalcon\Mvc\Micro\Collection

Groups Micro-Mvc handlers as controllers

$app = new \Phalcon\Mvc\Micro();

$collection = new Collection();

$collection->setHandler(
    new PostsController()
);

$collection->get("/posts/edit/{id}", "edit");

$app->mount($collection);

Method Summary

public CollectionInterface delete(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is DELETE. public CollectionInterface get(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is GET. public mixed getHandler() Returns the main handler public array getHandlers() Returns the registered handlers public string getPrefix() Returns the collection prefix if any public CollectionInterface head(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is HEAD. public bool isLazy() Returns if the main handler must be lazy loaded public CollectionInterface map(string $routePattern,callable $handler,string $name = null) Maps a route to a handler. public CollectionInterface mapVia(string $routePattern,callable $handler,mixed $method,string $name = null) Maps a route to a handler via methods. public CollectionInterface options(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is public CollectionInterface patch(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PATCH. public CollectionInterface post(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is POST. public CollectionInterface put(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PUT. public CollectionInterface setHandler(mixed $handler,bool $isLazy = false) Sets the main handler. public CollectionInterface setLazy( bool $isLazy ) Sets if the main handler must be lazy loaded public CollectionInterface setPrefix( string $prefix ) Sets a prefix for all routes added to the collection protected void addMap(mixed $method,string $routePattern,callable $handler,string $name = null) Internal function to add a handler to the group.

Properties

protected callable $handler
protected array $handlers = []
protected bool $isLazy = false
protected string $prefix = ""

Methods

Public · 16

delete()

public function delete(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is DELETE.

get()

public function get(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is GET.

getHandler()

public function getHandler(): mixed;

Returns the main handler

getHandlers()

public function getHandlers(): array;

Returns the registered handlers

getPrefix()

public function getPrefix(): string;

Returns the collection prefix if any

head()

public function head(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is HEAD.

isLazy()

public function isLazy(): bool;

Returns if the main handler must be lazy loaded

map()

public function map(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler.

mapVia()

public function mapVia(
    string $routePattern,
    callable $handler,
    mixed $method,
    string $name = null
): CollectionInterface;

Maps a route to a handler via methods.

$collection->mapVia(
    "/test",
    "indexAction",
    ["POST", "GET"],
    "test"
);

options()

public function options(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is OPTIONS.

patch()

public function patch(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is PATCH.

post()

public function post(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is POST.

put()

public function put(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is PUT.

setHandler()

public function setHandler(
    mixed $handler,
    bool $isLazy = false
): CollectionInterface;

Sets the main handler.

setLazy()

public function setLazy( bool $isLazy ): CollectionInterface;

Sets if the main handler must be lazy loaded

setPrefix()

public function setPrefix( string $prefix ): CollectionInterface;

Sets a prefix for all routes added to the collection

Protected · 1

addMap()

protected function addMap(
    mixed $method,
    string $routePattern,
    callable $handler,
    string $name = null
): void;

Internal function to add a handler to the group.

Mvc\Micro\CollectionInterface

Interface Source on GitHub

Phalcon\Mvc\Micro\CollectionInterface

Interface for Phalcon\Mvc\Micro\Collection

  • Phalcon\Mvc\Micro\CollectionInterface

Method Summary

public CollectionInterface delete(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is DELETE public CollectionInterface get(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is GET public mixed getHandler() Returns the main handler public array getHandlers() Returns the registered handlers public string getPrefix() Returns the collection prefix if any public CollectionInterface head(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is HEAD public bool isLazy() Returns if the main handler must be lazy loaded public CollectionInterface map(string $routePattern,callable $handler,string $name = null) Maps a route to a handler public CollectionInterface options(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is OPTIONS public CollectionInterface patch(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PATCH public CollectionInterface post(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is POST public CollectionInterface put(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PUT public CollectionInterface setHandler(mixed $handler,bool $isLazy = false) Sets the main handler public CollectionInterface setLazy( bool $isLazy ) Sets if the main handler must be lazy loaded public CollectionInterface setPrefix( string $prefix ) Sets a prefix for all routes added to the collection

Methods

Public · 15

delete()

public function delete(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is DELETE

get()

public function get(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is GET

getHandler()

public function getHandler(): mixed;

Returns the main handler

getHandlers()

public function getHandlers(): array;

Returns the registered handlers

getPrefix()

public function getPrefix(): string;

Returns the collection prefix if any

head()

public function head(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is HEAD

isLazy()

public function isLazy(): bool;

Returns if the main handler must be lazy loaded

map()

public function map(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler

options()

public function options(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is OPTIONS

patch()

public function patch(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is PATCH

post()

public function post(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is POST

put()

public function put(
    string $routePattern,
    callable $handler,
    string $name = null
): CollectionInterface;

Maps a route to a handler that only matches if the HTTP method is PUT

setHandler()

public function setHandler(
    mixed $handler,
    bool $isLazy = false
): CollectionInterface;

Sets the main handler

setLazy()

public function setLazy( bool $isLazy ): CollectionInterface;

Sets if the main handler must be lazy loaded

setPrefix()

public function setPrefix( string $prefix ): CollectionInterface;

Sets a prefix for all routes added to the collection

Mvc\Micro\Exception

Class Source on GitHub

Exceptions thrown in Phalcon\Mvc\Micro will use this class

Mvc\Micro\Exceptions\ContainerRequired

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\ErrorHandlerNotCallable

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\HandlerNotCallable

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Micro\Exceptions\InvalidRegisteredHandler

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\LazyHandlerNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $definition );

Mvc\Micro\Exceptions\MissingCollectionMainHandler

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\NoHandlersToMount

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\NoMatchedRouteHandler

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\NotFoundHandlerNotCallable

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\ResponseHandlerNotCallable

Class Source on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\LazyLoader

Class Source on GitHub

Phalcon\Mvc\Micro\LazyLoader

Lazy-Load of handlers for Mvc\Micro using auto-loading

  • Phalcon\Mvc\Micro\LazyLoader

Uses Phalcon\Mvc\Micro\Exceptions\LazyHandlerNotFound · Phalcon\Mvc\Model\BinderInterface

Method Summary

Properties

protected string $definition
protected object|null $handler = null

Methods

Public · 4

__construct()

public function __construct( string $definition );

Phalcon\Mvc\Micro\LazyLoader constructor

callMethod()

public function callMethod(
    string $method,
    mixed $arguments,
    BinderInterface $modelBinder = null
);

Calling __call method

getDefinition()

public function getDefinition(): string;

getHandler()

public function getHandler(): object|null;

Mvc\Micro\MiddlewareInterface

Interface Source on GitHub

Allows to implement Phalcon\Mvc\Micro middleware in classes

  • Phalcon\Mvc\Micro\MiddlewareInterface

Uses Phalcon\Mvc\Micro

Method Summary

Methods

Public · 1

call()

public function call( Micro $application );

Calls the middleware

Mvc\Model

Abstract Source on GitHub

Phalcon\Mvc\Model

Phalcon\Mvc\Model connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It‘s an implementation of the object-relational mapping (ORM).

A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models.

Phalcon\Mvc\Model is the first ORM written in Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use.

$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

if ($robot->save() === false) {
    echo "Umh, We can store robots: ";

    $messages = $robot->getMessages();

    foreach ($messages as $message) {
        echo $message;
    }
} else {
    echo "Great, a new robot was saved successfully!";
}

Magic property and method resolution:

__get($property) resolves in order: a relation alias (returning unsaved dirtyRelated records first, then a non-reusable single related model held in the related cache - resultsets and reusable relations are never served from that cache - otherwise the freshly fetched related records); then a get<Property>() getter when one exists; otherwise it raises an "undefined property" notice and returns null.

__call() / __callStatic($method, $arguments) resolve the findBy<Field>, findFirstBy<Field>, and countBy<Field> magic finders through invokeFinder(). The instance __call() additionally tries relation getters and a behavior/listener missingMethod() hook. An unresolved method throws Phalcon\Mvc\Model\Exceptions\MethodNotFound.

@template T of static

Uses JsonSerializable · Phalcon\Db\Adapter\AdapterInterface · Phalcon\Db\Column · Phalcon\Db\Enum · Phalcon\Db\Geometry\WkbParser · Phalcon\Db\RawValue · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Events\ManagerInterface · Phalcon\Filter\Validation\ValidationInterface · Phalcon\Messages\Message · Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\BehaviorInterface · Phalcon\Mvc\Model\Criteria · Phalcon\Mvc\Model\CriteriaInterface · Phalcon\Mvc\Model\Exception · Phalcon\Mvc\Model\Exceptions\BelongsToRequiresObject · Phalcon\Mvc\Model\Exceptions\BindTypeNotDefined · Phalcon\Mvc\Model\Exceptions\CannotResolveAttribute · Phalcon\Mvc\Model\Exceptions\ColumnNotInMap · Phalcon\Mvc\Model\Exceptions\ColumnNotInTableColumns · Phalcon\Mvc\Model\Exceptions\ColumnNotInTableMap · Phalcon\Mvc\Model\Exceptions\DataTypeNotDefined · Phalcon\Mvc\Model\Exceptions\IdentityNotInColumnMap · Phalcon\Mvc\Model\Exceptions\IdentityNotInTableColumns · Phalcon\Mvc\Model\Exceptions\InvalidDumpResultKey · Phalcon\Mvc\Model\Exceptions\InvalidFindParameters · Phalcon\Mvc\Model\Exceptions\InvalidModelsManagerService · Phalcon\Mvc\Model\Exceptions\InvalidModelsMetadataService · Phalcon\Mvc\Model\Exceptions\MethodNotFound · Phalcon\Mvc\Model\Exceptions\ModelOrmServicesUnavailable · Phalcon\Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet · Phalcon\Mvc\Model\Exceptions\PrimaryKeyRequired · Phalcon\Mvc\Model\Exceptions\PropertyNotAccessible · Phalcon\Mvc\Model\Exceptions\RecordCannotRefresh · Phalcon\Mvc\Model\Exceptions\RecordNotPersisted · Phalcon\Mvc\Model\Exceptions\RelationNotDefined · Phalcon\Mvc\Model\Exceptions\RelationRequiresObjectOrArray · Phalcon\Mvc\Model\Exceptions\SnapshotsDisabled · Phalcon\Mvc\Model\Exceptions\StaticMethodRequiresOneArgument · Phalcon\Mvc\Model\Exceptions\UpdateSnapshotDisabled · Phalcon\Mvc\Model\ManagerInterface · Phalcon\Mvc\Model\MetaDataInterface · Phalcon\Mvc\Model\Query · Phalcon\Mvc\Model\QueryInterface · Phalcon\Mvc\Model\Query\Builder · Phalcon\Mvc\Model\Query\BuilderInterface · Phalcon\Mvc\Model\Relation · Phalcon\Mvc\Model\RelationInterface · Phalcon\Mvc\Model\ResultInterface · Phalcon\Mvc\Model\Resultset · Phalcon\Mvc\Model\ResultsetInterface · Phalcon\Mvc\Model\TransactionInterface · Phalcon\Mvc\Model\ValidationFailed · Phalcon\Support\Collection · Phalcon\Support\Collection\CollectionInterface · Phalcon\Support\Settings · Serializable

Method Summary

public __call(string $method,array $arguments) Handles method calls when a method is not implemented public __callStatic(string $method,array $arguments) Handles method calls when a static method is not implemented public __construct(mixed $data = null,DiInterface $container = null,ManagerInterface $modelsManager = null) Phalcon\Mvc\Model constructor public __get( string $property ) Magic method to get related records using the relation alias as a public bool __isset( string $property ) Magic method to check if a property is a valid relation public array __serialize() Serializes a model public __set(string $property,mixed $value) Magic method to assign values to the the model public void __unserialize( array $data ) Unserializes an array to the model public void addBehavior( BehaviorInterface $behavior ) Setups a behavior in a model public ModelInterface appendMessage( MessageInterface $message ) Appends a customized message on the validation process public void appendMessagesFrom( mixed $model ) ** public ModelInterface assign(array $data,mixed $whiteList = null,mixed $dataColumnMap = null) Assigns values to a model from an array public double|ResultsetInterface average( array $parameters = [] ) Returns the average value on a column for a result-set of rows matching public ModelInterface cloneResult(ModelInterface $base,array $data,int $dirtyState = 0) Assigns values to a model from an array returning a new model public ModelInterface cloneResultMap(mixed $base,array $data,mixed $columnMap,int $dirtyState = 0,bool $keepSnapshots = null) Assigns values to a model from an array, returning a new model. public cloneResultMapHydrate(array $data,mixed $columnMap,int $hydrationMode) Returns an hydrated result based on the data and the column map public int|ResultsetInterface count( mixed $parameters = null ) Counts how many records match the specified conditions. public bool create() Inserts a model instance. If the instance already exists in the public bool delete() Deletes a model instance. Returning true on success or false otherwise. public bool doSave( CollectionInterface $visited ) Inserted or updates model instance, expects a visited list of objects. public array dump() Returns a simple representation of the object that can be used with public ResultsetInterface find( mixed $parameters = null ) Query for a set of records that match the specified conditions public mixed|null findFirst( mixed $parameters = null ) Query the first record that matches the specified conditions public bool fireEvent( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public bool fireEventCancel( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public array getChangedFields() Returns a list of changed values. public int getDirtyState() Returns one of the DIRTY_STATE_* constants telling if the record exists public EventsManagerInterface|null getEventsManager() Returns the custom events manager or null if there is no custom events manager public MessageInterface[] getMessages( mixed $filter = null ) Returns array of validation messages public ManagerInterface getModelsManager() Returns the models manager related to the entity instance public MetaDataInterface getModelsMetaData() {@inheritdoc} public array getOldSnapshotData() Returns the internal old snapshot data public int getOperationMade() Returns the type of the latest operation performed by the ORM public AdapterInterface getReadConnection() Gets the connection used to read data for the model public string getReadConnectionService() Returns the DependencyInjection connection service name used to read data public getRelated(string $alias,mixed $arguments = null) Returns related records based on defined relations public string|null getSchema() Returns schema name where the mapped table is located public array getSnapshotData() Returns the internal snapshot data public string getSource() Returns the table name mapped in the model public TransactionInterface|null getTransaction() public array getUpdatedFields() Returns a list of updated values. public AdapterInterface getWriteConnection() Gets the connection used to write data to the model public string getWriteConnectionService() Returns the DependencyInjection connection service name used to write public bool hasChanged(mixed $fieldName = null,bool $allFields = false) Check if a specific attribute has changed public bool hasSnapshotData() Checks if the object has internal snapshot data public bool hasUpdated(mixed $fieldName = null,bool $allFields = false) Check if a specific attribute was updated public bool isRelationshipLoaded( string $relationshipAlias ) Checks if saved related records have already been loaded. public array jsonSerialize() Serializes the object for json_encode public mixed maximum( mixed $parameters = null ) Returns the maximum value of a column for a result-set of rows that match public mixed minimum( mixed $parameters = null ) Returns the minimum value of a column for a result-set of rows that match public CriteriaInterface query( DiInterface $container = null ) Create a criteria for a specific model public mixed|null readAttribute( string $attribute ) Reads an attribute value by its name public ModelInterface refresh() Refreshes the model attributes re-querying the record from the database public bool save() Inserts or updates a model instance. Returning true on success or false public string|null serialize() Serializes the object ignoring connections, services, related objects or public void setConnectionService( string $connectionService ) Sets the DependencyInjection connection service name public ModelInterface|bool setDirtyState( int $dirtyState ) Sets the dirty state of the object using one of the DIRTY_STATE_* constants public setEventsManager( EventsManagerInterface $eventsManager ) Sets a custom events manager public setOldSnapshotData(array $data,mixed $columnMap = null) Sets the record's old snapshot data. public void setReadConnectionService( string $connectionService ) Sets the DependencyInjection connection service name used to read data public void setSnapshotData(array $data,mixed $columnMap = null) Sets the record's snapshot data. public ModelInterface setSync(mixed $elements = null,bool $enabled = true) Marks one or more many-to-many relationships to be synchronized (or not) public ModelInterface setTransaction( TransactionInterface $transaction ) Sets a transaction related to the Model instance public void setWriteConnectionService( string $connectionService ) Sets the DependencyInjection connection service name used to write data public void setup( array $options ) Enables/disables options in the ORM. public void skipOperation( bool $skip ) Skips the current operation forcing a success state public double|ResultsetInterface sum( mixed $parameters = null ) Calculates the sum on a column for a result-set of rows that match the public array toArray(mixed $columns = null,mixed $useGetter = true) Returns the instance as an array representation public void unserialize( string $data ) Unserializes the object from a serialized string public bool update() Updates a model instance. If the instance does not exist in the public bool validationHasFailed() Check whether validation process has generated any messages public void writeAttribute(string $attribute,mixed $value) Writes an attribute value by its name protected void allowEmptyStringValues( array $attributes ) Sets a list of attributes that must be skipped from the protected Relation belongsTo(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a reverse 1-1 or n-1 relation between two models protected cancelOperation() Cancel the current operation protected bool checkForeignKeysRestrict() Reads "belongs to" relations and check the virtual foreign keys when protected bool checkForeignKeysReverseCascade() Reads both "hasMany" and "hasOne" relations and checks the virtual protected bool checkForeignKeysReverseRestrict() Reads both "hasMany" and "hasOne" relations and checks the virtual protected array collectRelatedToSave() Collects previously queried (belongs-to, has-one and has-one-through) protected bool doLowInsert(MetaDataInterface $metaData,AdapterInterface $connection,mixed $table,mixed $identityField) Sends a pre-build INSERT SQL statement to the relational database system protected bool doLowUpdate(MetaDataInterface $metaData,AdapterInterface $connection,mixed $table) Sends a pre-build UPDATE SQL statement to the relational database system protected getRelatedRecords(string $modelName,string $method,array $arguments) Returns related records defined relations depending on the method name. protected mixed groupResult(string $functionName,string $alias,mixed $parameters = null) Generate a PHQL SELECT statement for an aggregate protected bool has(MetaDataInterface $metaData,AdapterInterface $connection) Checks whether the current record already exists protected Relation hasMany(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a 1-n relation between two models protected Relation hasManyToMany(mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referenceModel,mixed $referencedFields,array $options = []) Setup an n-n relation between two models, through an intermediate protected Relation hasOne(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models protected Relation hasOneThrough(mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models, through an intermediate protected invokeFinder(string $method,array $arguments) Try to check if the query must invoke a finder protected void keepSnapshots( bool $keepSnapshot ) Sets if the model must keep the original record snapshot in memory protected bool possibleSetter(string $property,mixed $value) Check for, and attempt to use, possible setter. protected bool postSave(bool $success,bool $exists) Executes internal events after save a record protected bool postSaveRelatedRecords(AdapterInterface $connection,mixed $related,CollectionInterface $visited) Save the related records assigned in the has-one/has-many relations protected bool preSave(MetaDataInterface $metaData,bool $exists,mixed $identityField) Executes internal hooks before save a record protected bool preSaveRelatedRecords(AdapterInterface $connection,mixed $related,CollectionInterface $visited) Saves related records that must be stored prior to save the master record protected ModelInterface setSchema( string $schema ) Sets schema name where the mapped table is located protected ModelInterface setSource( string $source ) Sets the table name to which model should be mapped protected void skipAttributes( array $attributes ) Sets a list of attributes that must be skipped from the protected void skipAttributesOnCreate( array $attributes ) Sets a list of attributes that must be skipped from the protected void skipAttributesOnUpdate( array $attributes ) Sets a list of attributes that must be skipped from the protected void useDynamicUpdate( bool $dynamicUpdate ) Sets if a model must use dynamic update instead of the all-field update protected bool validate( ValidationInterface $validator ) Executes validators on every validation call

Constants

int DIRTY_STATE_DETACHED = 2
int DIRTY_STATE_PERSISTENT = 0
int DIRTY_STATE_TRANSIENT = 1
int OP_CREATE = 1
int OP_DELETE = 3
int OP_NONE = 0
int OP_UPDATE = 2
string TRANSACTION_INDEX = "transaction"

Properties

protected array $dirtyRelated = []
protected int $dirtyState = 1
protected array $errorMessages = []
protected ManagerInterface|null $modelsManager = null
protected MetaDataInterface|null $modelsMetaData = null
protected array $oldSnapshot = []
protected int $operationMade = 0
protected array $rawValues = []
protected array $related = []
protected bool $skipped = false
protected array $snapshot = []
protected array $syncRelated = [] Per-save many-to-many sync overrides, keyed by lowercased relation alias (or "*" wildcard) => bool. Cleared after each save().
protected TransactionInterface|null $transaction = null
protected string|null $uniqueKey = null
protected array $uniqueParams = []
protected array $uniqueTypes = []

Methods

Public · 72

__call()

public function __call(
    string $method,
    array $arguments
);

Handles method calls when a method is not implemented

__callStatic()

public static function __callStatic(
    string $method,
    array $arguments
);

Handles method calls when a static method is not implemented

__construct()

final public function __construct(
    mixed $data = null,
    DiInterface $container = null,
    ManagerInterface $modelsManager = null
);

Phalcon\Mvc\Model constructor

__get()

public function __get( string $property );

Magic method to get related records using the relation alias as a property

__isset()

public function __isset( string $property ): bool;

Magic method to check if a property is a valid relation

__serialize()

public function __serialize(): array;

Serializes a model

__set()

public function __set(
    string $property,
    mixed $value
);

Magic method to assign values to the the model

__unserialize()

public function __unserialize( array $data ): void;

Unserializes an array to the model

addBehavior()

public function addBehavior( BehaviorInterface $behavior ): void;

Setups a behavior in a model

use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;

class Robots extends Model
{
    public function initialize()
    {
        $this->addBehavior(
            new Timestampable(
                [
                    "beforeCreate" => [
                        "field"  => "created_at",
                        "format" => "Y-m-d",
                    ],
                ]
            )
        );

        $this->addBehavior(
            new Timestampable(
                [
                    "beforeUpdate" => [
                        "field"  => "updated_at",
                        "format" => "Y-m-d",
                    ],
                ]
            )
        );
    }
}

appendMessage()

public function appendMessage( MessageInterface $message ): ModelInterface;

Appends a customized message on the validation process

use Phalcon\Mvc\Model;
use Phalcon\Messages\Message as Message;

class Robots extends Model
{
    public function beforeSave()
    {
        if ($this->name === "Peter") {
            $message = new Message(
                "Sorry, but a robot cannot be named Peter"
            );

            $this->appendMessage($message);
        }
    }
}

appendMessagesFrom()

public inline function appendMessagesFrom( mixed $model ): void;

** Append messages to this model from another Model.

assign()

public function assign(
    array $data,
    mixed $whiteList = null,
    mixed $dataColumnMap = null
): ModelInterface;

Assigns values to a model from an array

$robot->assign(
    [
        "type" => "mechanical",
        "name" => "Astro Boy",
        "year" => 1952,
    ]
);

// Assign by db row, column map needed
$robot->assign(
    $dbRow,
    [
        "db_type" => "type",
        "db_name" => "name",
        "db_year" => "year",
    ]
);

// Allow assign only name and year
$robot->assign(
    $_POST,
    [
        "name",
        "year",
    ]
);

// By default assign method will use setters if exist, you can disable it by using ini_set to directly use properties

ini_set("phalcon.orm.disable_assign_setters", true);

$robot->assign(
    $_POST,
    [
        "name",
        "year",
    ]
);

average()

public static function average( array $parameters = [] ): double|ResultsetInterface;

Returns the average value on a column for a result-set of rows matching the specified conditions.

Returned value will be a float for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the average of each group.

// What's the average price of robots?
$average = Robots::average(
    [
        "column" => "price",
    ]
);

echo "The average price is ", $average, "\n";

// What's the average price of mechanical robots?
$average = Robots::average(
    [
        "type = 'mechanical'",
        "column" => "price",
    ]
);

echo "The average price of mechanical robots is ", $average, "\n";

cloneResult()

public static function cloneResult(
    ModelInterface $base,
    array $data,
    int $dirtyState = 0
): ModelInterface;

Assigns values to a model from an array returning a new model

$robot = Phalcon\Mvc\Model::cloneResult(
    new Robots(),
    [
        "type" => "mechanical",
        "name" => "Astro Boy",
        "year" => 1952,
    ]
);

cloneResultMap()

public static function cloneResultMap(
    mixed $base,
    array $data,
    mixed $columnMap,
    int $dirtyState = 0,
    bool $keepSnapshots = null
): ModelInterface;

Assigns values to a model from an array, returning a new model.

$robot = \Phalcon\Mvc\Model::cloneResultMap(
    new Robots(),
    [
        "type" => "mechanical",
        "name" => "Astro Boy",
        "year" => 1952,
    ]
);

cloneResultMapHydrate()

public static function cloneResultMapHydrate(
    array $data,
    mixed $columnMap,
    int $hydrationMode
);

Returns an hydrated result based on the data and the column map

count()

public static function count( mixed $parameters = null ): int|ResultsetInterface;

Counts how many records match the specified conditions.

Returns an integer for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the count of each group.

// How many robots are there?
$number = Robots::count();

echo "There are ", $number, "\n";

// How many mechanical robots are there?
$number = Robots::count("type = 'mechanical'");

echo "There are ", $number, " mechanical robots\n";

create()

public function create(): bool;

Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise.

// Creating a new robot
$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

$robot->create();

// Passing an array to create
$robot = new Robots();

$robot->assign(
    [
        "type" => "mechanical",
        "name" => "Astro Boy",
        "year" => 1952,
    ]
);

$robot->create();

delete()

public function delete(): bool;

Deletes a model instance. Returning true on success or false otherwise.

$robot = Robots::findFirst("id=100");

$robot->delete();

$robots = Robots::find("type = 'mechanical'");

foreach ($robots as $robot) {
    $robot->delete();
}

doSave()

public function doSave( CollectionInterface $visited ): bool;

Inserted or updates model instance, expects a visited list of objects.

dump()

public function dump(): array;

Returns a simple representation of the object that can be used with var_dump()

var_dump(
    $robot->dump()
);

find()

public static function find( mixed $parameters = null ): ResultsetInterface;

Query for a set of records that match the specified conditions

// How many robots are there?
$robots = Robots::find();

echo "There are ", count($robots), "\n";

// How many mechanical robots are there?
$robots = Robots::find(
    "type = 'mechanical'"
);

echo "There are ", count($robots), "\n";

// Get and print virtual robots ordered by name
$robots = Robots::find(
    [
        "type = 'virtual'",
        "order" => "name",
    ]
);

foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// Get first 100 virtual robots ordered by name
$robots = Robots::find(
    [
        "type = 'virtual'",
        "order" => "name",
        "limit" => 100,
    ]
);

foreach ($robots as $robot) {
    echo $robot->name, "\n";
}

// encapsulate find it into an running transaction esp. useful for application unit-tests
// or complex business logic where we wanna control which transactions are used.

$myTransaction = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction->begin();

$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);

$newRobot->assign(
    [
        'name' => 'test',
        'type' => 'mechanical',
        'year' => 1944,
    ]
);

$newRobot->save();

$resultInsideTransaction = Robot::find(
    [
        'name' => 'test',
        Model::TRANSACTION_INDEX => $myTransaction,
    ]
);

$resultOutsideTransaction = Robot::find(['name' => 'test']);

foreach ($setInsideTransaction as $robot) {
    echo $robot->name, "\n";
}

foreach ($setOutsideTransaction as $robot) {
    echo $robot->name, "\n";
}

// reverts all not commited changes
$myTransaction->rollback();

// creating two different transactions
$myTransaction1 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction1->begin();
$myTransaction2 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction2->begin();

 // add a new robots
$firstNewRobot = new Robot();
$firstNewRobot->setTransaction($myTransaction1);
$firstNewRobot->assign(
    [
        'name' => 'first-transaction-robot',
        'type' => 'mechanical',
        'year' => 1944,
    ]
);
$firstNewRobot->save();

$secondNewRobot = new Robot();
$secondNewRobot->setTransaction($myTransaction2);
$secondNewRobot->assign(
    [
        'name' => 'second-transaction-robot',
        'type' => 'fictional',
        'year' => 1984,
    ]
);
$secondNewRobot->save();

// this transaction will find the robot.
$resultInFirstTransaction = Robot::find(
    [
        'name'                   => 'first-transaction-robot',
        Model::TRANSACTION_INDEX => $myTransaction1,
    ]
);

// this transaction won't find the robot.
$resultInSecondTransaction = Robot::find(
    [
        'name'                   => 'first-transaction-robot',
        Model::TRANSACTION_INDEX => $myTransaction2,
    ]
);

// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
    [
        'name' => 'first-transaction-robot',
    ]
);

// this transaction won't find the robot.
$resultInFirstTransaction = Robot::find(
    [
        'name'                   => 'second-transaction-robot',
        Model::TRANSACTION_INDEX => $myTransaction2,
    ]
);

// this transaction will find the robot.
$resultInSecondTransaction = Robot::find(
    [
        'name'                   => 'second-transaction-robot',
        Model::TRANSACTION_INDEX => $myTransaction1,
    ]
);

// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
    [
        'name' => 'second-transaction-robot',
    ]
);

$transaction1->rollback();
$transaction2->rollback();

findFirst()

public static function findFirst( mixed $parameters = null ): mixed|null;

Query the first record that matches the specified conditions

// What's the first robot in robots table?
$robot = Robots::findFirst();

echo "The robot name is ", $robot->name;

// What's the first mechanical robot in robots table?
$robot = Robots::findFirst(
    "type = 'mechanical'"
);

echo "The first mechanical robot name is ", $robot->name;

// Get first virtual robot ordered by name
$robot = Robots::findFirst(
    [
        "type = 'virtual'",
        "order" => "name",
    ]
);

echo "The first virtual robot name is ", $robot->name;

// behaviour with transaction
$myTransaction = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction->begin();

$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->assign(
    [
        'name' => 'test',
        'type' => 'mechanical',
        'year' => 1944,
    ]
);
$newRobot->save();

$findsARobot = Robot::findFirst(
    [
        'name'                   => 'test',
        Model::TRANSACTION_INDEX => $myTransaction,
    ]
);

$doesNotFindARobot = Robot::findFirst(
    [
        'name' => 'test',
    ]
);

var_dump($findARobot);
var_dump($doesNotFindARobot);

$transaction->commit();

$doesFindTheRobotNow = Robot::findFirst(
    [
        'name' => 'test',
    ]
);

fireEvent()

public function fireEvent( string $eventName ): bool;

Fires an event, implicitly calls behaviors and listeners in the events manager are notified

fireEventCancel()

public function fireEventCancel( string $eventName ): bool;

Fires an event, implicitly calls behaviors and listeners in the events manager are notified This method stops if one of the callbacks/listeners returns bool false

getChangedFields()

public function getChangedFields(): array;

Returns a list of changed values.

$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []

$robots->deleted = 'Y';

$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]

getDirtyState()

public function getDirtyState(): int;

Returns one of the DIRTY_STATE_* constants telling if the record exists in the database or not

getEventsManager()

public function getEventsManager(): EventsManagerInterface|null;

Returns the custom events manager or null if there is no custom events manager

getMessages()

public function getMessages( mixed $filter = null ): MessageInterface[];

Returns array of validation messages

$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

if ($robot->save() === false) {
    echo "Umh, We can't store robots right now ";

    $messages = $robot->getMessages();

    foreach ($messages as $message) {
        echo $message;
    }
} else {
    echo "Great, a new robot was saved successfully!";
}

getModelsManager()

public function getModelsManager(): ManagerInterface;

Returns the models manager related to the entity instance

getModelsMetaData()

public function getModelsMetaData(): MetaDataInterface;

{@inheritdoc}

getOldSnapshotData()

public function getOldSnapshotData(): array;

Returns the internal old snapshot data

getOperationMade()

public function getOperationMade(): int;

Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants

getReadConnection()

final public function getReadConnection(): AdapterInterface;

Gets the connection used to read data for the model

getReadConnectionService()

final public function getReadConnectionService(): string;

Returns the DependencyInjection connection service name used to read data related the model

getRelated()

public function getRelated(
    string $alias,
    mixed $arguments = null
);

Returns related records based on defined relations

getSchema()

final public function getSchema(): string|null;

Returns schema name where the mapped table is located

getSnapshotData()

public function getSnapshotData(): array;

Returns the internal snapshot data

getSource()

final public function getSource(): string;

Returns the table name mapped in the model

getTransaction()

public function getTransaction(): TransactionInterface|null;

getUpdatedFields()

public function getUpdatedFields(): array;

Returns a list of updated values.

$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []

$robots->deleted = 'Y';

$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]
$robots->save();
print_r($robots->getChangedFields()); // []
print_r($robots->getUpdatedFields()); // ["deleted"]

getWriteConnection()

final public function getWriteConnection(): AdapterInterface;

Gets the connection used to write data to the model

getWriteConnectionService()

final public function getWriteConnectionService(): string;

Returns the DependencyInjection connection service name used to write data related to the model

hasChanged()

public function hasChanged(
    mixed $fieldName = null,
    bool $allFields = false
): bool;

Check if a specific attribute has changed This only works if the model is keeping data snapshots

$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

$robot->create();

$robot->type = "hydraulic";

$hasChanged = $robot->hasChanged("type"); // returns true
$hasChanged = $robot->hasChanged(["type", "name"]); // returns true
$hasChanged = $robot->hasChanged(["type", "name"], true); // returns false

hasSnapshotData()

public function hasSnapshotData(): bool;

Checks if the object has internal snapshot data

hasUpdated()

public function hasUpdated(
    mixed $fieldName = null,
    bool $allFields = false
): bool;

Check if a specific attribute was updated This only works if the model is keeping data snapshots

isRelationshipLoaded()

public function isRelationshipLoaded( string $relationshipAlias ): bool;

Checks if saved related records have already been loaded.

Only returns true if the records were previously fetched through the model without any additional parameters.

$robot = Robots::findFirst();
var_dump($robot->isRelationshipLoaded('robotsParts')); // false

$robotsParts = $robot->getRobotsParts(['id > 0']);
var_dump($robot->isRelationshipLoaded('robotsParts')); // false

$robotsParts = $robot->getRobotsParts(); // or $robot->robotsParts
var_dump($robot->isRelationshipLoaded('robotsParts')); // true

$robot->robotsParts = [new RobotsParts()];
var_dump($robot->isRelationshipLoaded('robotsParts')); // false

jsonSerialize()

public function jsonSerialize(): array;

Serializes the object for json_encode

echo json_encode($robot);

maximum()

public static function maximum( mixed $parameters = null ): mixed;

Returns the maximum value of a column for a result-set of rows that match the specified conditions

// What is the maximum robot id?
$id = Robots::maximum(
    [
        "column" => "id",
    ]
);

echo "The maximum robot id is: ", $id, "\n";

// What is the maximum id of mechanical robots?
$sum = Robots::maximum(
    [
        "type = 'mechanical'",
        "column" => "id",
    ]
);

echo "The maximum robot id of mechanical robots is ", $id, "\n";

minimum()

public static function minimum( mixed $parameters = null ): mixed;

Returns the minimum value of a column for a result-set of rows that match the specified conditions

// What is the minimum robot id?
$id = Robots::minimum(
    [
        "column" => "id",
    ]
);

echo "The minimum robot id is: ", $id;

// What is the minimum id of mechanical robots?
$sum = Robots::minimum(
    [
        "type = 'mechanical'",
        "column" => "id",
    ]
);

echo "The minimum robot id of mechanical robots is ", $id;

query()

public static function query( DiInterface $container = null ): CriteriaInterface;

Create a criteria for a specific model

readAttribute()

public function readAttribute( string $attribute ): mixed|null;

Reads an attribute value by its name

echo $robot->readAttribute("name");

refresh()

public function refresh(): ModelInterface;

Refreshes the model attributes re-querying the record from the database

save()

public function save(): bool;

Inserts or updates a model instance. Returning true on success or false otherwise.

// Creating a new robot
$robot = new Robots();

$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;

$robot->save();

// Updating a robot name
$robot = Robots::findFirst("id = 100");

$robot->name = "Biomass";

$robot->save();

serialize()

public function serialize(): string|null;

Serializes the object ignoring connections, services, related objects or static properties

setConnectionService()

final public function setConnectionService( string $connectionService ): void;

Sets the DependencyInjection connection service name

setDirtyState()

public function setDirtyState( int $dirtyState ): ModelInterface|bool;

Sets the dirty state of the object using one of the DIRTY_STATE_* constants

setEventsManager()

public function setEventsManager( EventsManagerInterface $eventsManager );

Sets a custom events manager

setOldSnapshotData()

public function setOldSnapshotData(
    array $data,
    mixed $columnMap = null
);

Sets the record's old snapshot data. This method is used internally to set old snapshot data when the model was set up to keep snapshot data

setReadConnectionService()

final public function setReadConnectionService( string $connectionService ): void;

Sets the DependencyInjection connection service name used to read data

setSnapshotData()

public function setSnapshotData(
    array $data,
    mixed $columnMap = null
): void;

Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data

setSync()

public function setSync(
    mixed $elements = null,
    bool $enabled = true
): ModelInterface;

Marks one or more many-to-many relationships to be synchronized (or not) on the next save() call, overriding the relation's sync option for that save only. The flag is cleared after save().

When syncing is enabled, intermediate rows for related records no longer present in the assigned array are deleted.

// Sync only the "tags" relationship on this save
$post->setSync("tags")->save();

// Sync every many-to-many relationship on this save
$post->setSync()->save();

// Disable syncing for every relationship on this save
$post->setSync("*", false)->save();

// Disable syncing for specific relationships on this save
$post->setSync(["tags", "categories"], false)->save();

setTransaction()

public function setTransaction( TransactionInterface $transaction ): ModelInterface;

Sets a transaction related to the Model instance

use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;

try {
    $txManager = new TxManager();

    $transaction = $txManager->get();

    $robot = new Robots();

    $robot->setTransaction($transaction);

    $robot->name       = "WALL·E";
    $robot->created_at = date("Y-m-d");

    if ($robot->save() === false) {
        $transaction->rollback("Can't save robot");
    }

    $robotPart = new RobotParts();

    $robotPart->setTransaction($transaction);

    $robotPart->type = "head";

    if ($robotPart->save() === false) {
        $transaction->rollback("Robot part cannot be saved");
    }

    $transaction->commit();
} catch (TxFailed $e) {
    echo "Failed, reason: ", $e->getMessage();
}

setWriteConnectionService()

final public function setWriteConnectionService( string $connectionService ): void;

Sets the DependencyInjection connection service name used to write data

setup()

public static function setup( array $options ): void;

Enables/disables options in the ORM.

The options are written to process-global Phalcon\Support\Settings (orm.* flags) and therefore affect every model in the process at once. Call this once during bootstrap; it is not per-model or per-container configuration, and one application's setup() reconfigures the ORM for every other user in the same process.

skipOperation()

public function skipOperation( bool $skip ): void;

Skips the current operation forcing a success state

sum()

public static function sum( mixed $parameters = null ): double|ResultsetInterface;

Calculates the sum on a column for a result-set of rows that match the specified conditions

// How much are all robots?
$sum = Robots::sum(
    [
        "column" => "price",
    ]
);

echo "The total price of robots is ", $sum, "\n";

// How much are mechanical robots?
$sum = Robots::sum(
    [
        "type = 'mechanical'",
        "column" => "price",
    ]
);

echo "The total price of mechanical robots is  ", $sum, "\n";

toArray()

public function toArray(
    mixed $columns = null,
    mixed $useGetter = true
): array;

Returns the instance as an array representation

print_r(
    $robot->toArray()
);

unserialize()

public function unserialize( string $data ): void;

Unserializes the object from a serialized string

update()

public function update(): bool;

Updates a model instance. If the instance does not exist in the persistence it will throw an exception. Returning true on success or false otherwise.

<?php

use MyApp\Models\Invoices;

$invoice = Invoices::findFirst('inv_id = 4');

$invoice->inv_total = 120;

$invoice->update();

NOTE

When retrieving the record with findFirst(), you need to get the full object back (no columns definition) but also retrieve it using the primary key. If not, the ORM will issue an INSERT instead of UPDATE.

validationHasFailed()

public function validationHasFailed(): bool;

Check whether validation process has generated any messages

use Phalcon\Mvc\Model;
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\ExclusionIn;

class Subscriptors extends Model
{
    public function validation()
    {
        $validator = new Validation();

        $validator->validate(
            "status",
            new ExclusionIn(
                [
                    "domain" => [
                        "A",
                        "I",
                    ],
                ]
            )
        );

        return $this->validate($validator);
    }
}

writeAttribute()

public function writeAttribute(
    string $attribute,
    mixed $value
): void;

Writes an attribute value by its name

$robot->writeAttribute("name", "Rosey");
Protected · 30

allowEmptyStringValues()

protected function allowEmptyStringValues( array $attributes ): void;

Sets a list of attributes that must be skipped from the generated UPDATE statement

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->allowEmptyStringValues(
            [
                "name",
            ]
        );
    }
}

belongsTo()

protected function belongsTo(
    mixed $fields,
    string $referenceModel,
    mixed $referencedFields,
    array $options = []
): Relation;

Setup a reverse 1-1 or n-1 relation between two models

class RobotsParts extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->belongsTo(
            "robots_id",
            Robots::class,
            "id"
        );
    }
}

cancelOperation()

protected function cancelOperation();

Cancel the current operation

checkForeignKeysRestrict()

final protected function checkForeignKeysRestrict(): bool;

Reads "belongs to" relations and check the virtual foreign keys when inserting or updating records to verify that inserted/updated values are present in the related entity

checkForeignKeysReverseCascade()

final protected function checkForeignKeysReverseCascade(): bool;

Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (cascade) when deleting records

checkForeignKeysReverseRestrict()

final protected function checkForeignKeysReverseRestrict(): bool;

Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (restrict) when deleting records

collectRelatedToSave()

protected function collectRelatedToSave(): array;

Collects previously queried (belongs-to, has-one and has-one-through) related records along with freshly added one

doLowInsert()

protected function doLowInsert(
    MetaDataInterface $metaData,
    AdapterInterface $connection,
    mixed $table,
    mixed $identityField
): bool;

Sends a pre-build INSERT SQL statement to the relational database system

doLowUpdate()

protected function doLowUpdate(
    MetaDataInterface $metaData,
    AdapterInterface $connection,
    mixed $table
): bool;

Sends a pre-build UPDATE SQL statement to the relational database system

getRelatedRecords()

protected function getRelatedRecords(
    string $modelName,
    string $method,
    array $arguments
);

Returns related records defined relations depending on the method name. Returns false if the relation is non-existent.

groupResult()

protected static function groupResult(
    string $functionName,
    string $alias,
    mixed $parameters = null
): mixed;

Generate a PHQL SELECT statement for an aggregate

has()

protected function has(
    MetaDataInterface $metaData,
    AdapterInterface $connection
): bool;

Checks whether the current record already exists

hasMany()

protected function hasMany(
    mixed $fields,
    string $referenceModel,
    mixed $referencedFields,
    array $options = []
): Relation;

Setup a 1-n relation between two models

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasMany(
            "id",
            RobotsParts::class,
            "robots_id"
        );
    }
}

hasManyToMany()

protected function hasManyToMany(
    mixed $fields,
    string $intermediateModel,
    mixed $intermediateFields,
    mixed $intermediateReferencedFields,
    string $referenceModel,
    mixed $referencedFields,
    array $options = []
): Relation;

Setup an n-n relation between two models, through an intermediate relation

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        // Setup a many-to-many relation to Parts through RobotsParts
        $this->hasManyToMany(
            "id",
            RobotsParts::class,
            "robots_id",
            "parts_id",
            Parts::class,
            "id",
        );
    }
}

hasOne()

protected function hasOne(
    mixed $fields,
    string $referenceModel,
    mixed $referencedFields,
    array $options = []
): Relation;

Setup a 1-1 relation between two models

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasOne(
            "id",
            RobotsDescription::class,
            "robots_id"
        );
    }
}

hasOneThrough()

protected function hasOneThrough(
    mixed $fields,
    string $intermediateModel,
    mixed $intermediateFields,
    mixed $intermediateReferencedFields,
    string $referenceModel,
    mixed $referencedFields,
    array $options = []
): Relation;

Setup a 1-1 relation between two models, through an intermediate relation

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        // Setup a 1-1 relation to one item from Parts through RobotsParts
        $this->hasOneThrough(
            "id",
            RobotsParts::class,
            "robots_id",
            "parts_id",
            Parts::class,
            "id",
        );
    }
}

invokeFinder()

protected final static function invokeFinder(
    string $method,
    array $arguments
);

Try to check if the query must invoke a finder

keepSnapshots()

protected function keepSnapshots( bool $keepSnapshot ): void;

Sets if the model must keep the original record snapshot in memory

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->keepSnapshots(true);
    }
}

possibleSetter()

final protected function possibleSetter(
    string $property,
    mixed $value
): bool;

Check for, and attempt to use, possible setter.

postSave()

protected function postSave(
    bool $success,
    bool $exists
): bool;

Executes internal events after save a record

postSaveRelatedRecords()

protected function postSaveRelatedRecords(
    AdapterInterface $connection,
    mixed $related,
    CollectionInterface $visited
): bool;

Save the related records assigned in the has-one/has-many relations

preSave()

protected function preSave(
    MetaDataInterface $metaData,
    bool $exists,
    mixed $identityField
): bool;

Executes internal hooks before save a record

preSaveRelatedRecords()

protected function preSaveRelatedRecords(
    AdapterInterface $connection,
    mixed $related,
    CollectionInterface $visited
): bool;

Saves related records that must be stored prior to save the master record

setSchema()

final protected function setSchema( string $schema ): ModelInterface;

Sets schema name where the mapped table is located

setSource()

final protected function setSource( string $source ): ModelInterface;

Sets the table name to which model should be mapped

skipAttributes()

protected function skipAttributes( array $attributes ): void;

Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->skipAttributes(
            [
                "price",
            ]
        );
    }
}

skipAttributesOnCreate()

protected function skipAttributesOnCreate( array $attributes ): void;

Sets a list of attributes that must be skipped from the generated INSERT statement

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->skipAttributesOnCreate(
            [
                "created_at",
            ]
        );
    }
}

skipAttributesOnUpdate()

protected function skipAttributesOnUpdate( array $attributes ): void;

Sets a list of attributes that must be skipped from the generated UPDATE statement

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->skipAttributesOnUpdate(
            [
                "modified_in",
            ]
        );
    }
}

useDynamicUpdate()

protected function useDynamicUpdate( bool $dynamicUpdate ): void;

Sets if a model must use dynamic update instead of the all-field update

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->useDynamicUpdate(true);
    }
}

validate()

protected function validate( ValidationInterface $validator ): bool;

Executes validators on every validation call

use Phalcon\Mvc\Model;
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\ExclusionIn;

class Subscriptors extends Model
{
    public function validation()
    {
        $validator = new Validation();

        $validator->add(
            "status",
            new ExclusionIn(
                [
                    "domain" => [
                        "A",
                        "I",
                    ],
                ]
            )
        );

        return $this->validate($validator);
    }
}

Mvc\ModelInterface

Interface Source on GitHub

Phalcon\Mvc\ModelInterface

Interface for Phalcon\Mvc\Model

@template T

  • Phalcon\Mvc\ModelInterface

Uses Phalcon\Db\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Messages\MessageInterface · Phalcon\Mvc\Model\CriteriaInterface · Phalcon\Mvc\Model\MetaDataInterface · Phalcon\Mvc\Model\ResultInterface · Phalcon\Mvc\Model\Resultset · Phalcon\Mvc\Model\ResultsetInterface · Phalcon\Mvc\Model\TransactionInterface

Method Summary

public ModelInterface appendMessage( MessageInterface $message ) Appends a customized message on the validation process public ModelInterface assign(array $data,mixed $whiteList = null,mixed $dataColumnMap = null) Assigns values to a model from an array public double|ResultsetInterface average( array $parameters = [] ) Allows to calculate the average value on a column matching the specified public ModelInterface cloneResult(ModelInterface $base,array $data,int $dirtyState = 0) Assigns values to a model from an array returning a new model public ModelInterface cloneResultMap(mixed $base,array $data,mixed $columnMap,int $dirtyState = 0,bool $keepSnapshots = false) Assigns values to a model from an array returning a new model public cloneResultMapHydrate(array $data,mixed $columnMap,int $hydrationMode) Returns an hydrated result based on the data and the column map public int|ResultsetInterface count( mixed $parameters = null ) Allows to count how many records match the specified conditions public bool create() Inserts a model instance. If the instance already exists in the public bool delete() Deletes a model instance. Returning true on success or false otherwise. public find( mixed $parameters = null ) Allows to query a set of records that match the specified conditions. public mixed|null findFirst( mixed $parameters = null ) Allows to query the first record that match the specified conditions public bool fireEvent( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public bool fireEventCancel( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public int getDirtyState() Returns one of the DIRTY_STATE_* constants telling if the record exists public MessageInterface[] getMessages() Returns array of validation messages public MetaDataInterface getModelsMetaData() Returns the models meta-data service related to the entity instance. public int getOperationMade() Returns the type of the latest operation performed by the ORM public AdapterInterface getReadConnection() Gets internal database connection public string getReadConnectionService() Returns DependencyInjection connection service used to read data public getRelated(string $alias,mixed $arguments = null) Returns related records based on defined relations public string|null getSchema() Returns schema name where table mapped is located public string getSource() Returns table name mapped in the model public AdapterInterface getWriteConnection() Gets internal database connection public string getWriteConnectionService() Returns DependencyInjection connection service used to write data public mixed maximum( mixed $parameters = null ) Allows to get the maximum value of a column that match the specified public mixed minimum( mixed $parameters = null ) Allows to get the minimum value of a column that match the specified public CriteriaInterface query( DiInterface $container = null ) Create a criteria for a specific model public ModelInterface refresh() Refreshes the model attributes re-querying the record from the database public bool save() Inserts or updates a model instance. Returning true on success or false public void setConnectionService( string $connectionService ) Sets both read/write connection services public ModelInterface|bool setDirtyState( int $dirtyState ) Sets the dirty state of the object using one of the DIRTY_STATE_* public void setReadConnectionService( string $connectionService ) Sets the DependencyInjection connection service used to read data public void setSnapshotData(array $data,mixed $columnMap = null) Sets the record's snapshot data. This method is used internally to set public ModelInterface setSync(mixed $elements = null,bool $enabled = true) Marks one or more many-to-many relationships to be synchronized (or not) public ModelInterface setTransaction( TransactionInterface $transaction ) Sets a transaction related to the Model instance public void setWriteConnectionService( string $connectionService ) Sets the DependencyInjection connection service used to write data public void skipOperation( bool $skip ) Skips the current operation forcing a success state public double|ResultsetInterface sum( mixed $parameters = null ) Allows to calculate a sum on a column that match the specified conditions public bool update() Updates a model instance. If the instance does not exist in the public bool validationHasFailed() Check whether validation process has generated any messages

Methods

Public · 40

appendMessage()

public function appendMessage( MessageInterface $message ): ModelInterface;

Appends a customized message on the validation process

assign()

public function assign(
    array $data,
    mixed $whiteList = null,
    mixed $dataColumnMap = null
): ModelInterface;

Assigns values to a model from an array

average()

public static function average( array $parameters = [] ): double|ResultsetInterface;

Allows to calculate the average value on a column matching the specified conditions

cloneResult()

public static function cloneResult(
    ModelInterface $base,
    array $data,
    int $dirtyState = 0
): ModelInterface;

Assigns values to a model from an array returning a new model

cloneResultMap()

public static function cloneResultMap(
    mixed $base,
    array $data,
    mixed $columnMap,
    int $dirtyState = 0,
    bool $keepSnapshots = false
): ModelInterface;

Assigns values to a model from an array returning a new model

cloneResultMapHydrate()

public static function cloneResultMapHydrate(
    array $data,
    mixed $columnMap,
    int $hydrationMode
);

Returns an hydrated result based on the data and the column map

count()

public static function count( mixed $parameters = null ): int|ResultsetInterface;

Allows to count how many records match the specified conditions

Returns an integer for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the count of each group.

create()

public function create(): bool;

Inserts a model instance. If the instance already exists in the persistence it will throw an exception. Returning true on success or false otherwise.

delete()

public function delete(): bool;

Deletes a model instance. Returning true on success or false otherwise.

find()

public static function find( mixed $parameters = null );

Allows to query a set of records that match the specified conditions.

This is one of four ways to express a query against a model, each with an intended lane:

  • find-parameter arrays (this method) for simple lookups;
  • Phalcon\Mvc\Model\Query\Builder as the canonical programmatic API;
  • Phalcon\Mvc\Model\Criteria as request-bound convenience;
  • raw PHQL via Phalcon\Mvc\Model\Query for everything else.

findFirst()

public static function findFirst( mixed $parameters = null ): mixed|null;

Allows to query the first record that match the specified conditions

TODO: Current method signature must be reviewed in v5. As it must return only ?ModelInterface (it also returns Row). @see https://github.com/phalcon/cphalcon/issues/15212 @see https://github.com/phalcon/cphalcon/issues/15883

fireEvent()

public function fireEvent( string $eventName ): bool;

Fires an event, implicitly calls behaviors and listeners in the events manager are notified

fireEventCancel()

public function fireEventCancel( string $eventName ): bool;

Fires an event, implicitly calls behaviors and listeners in the events manager are notified. This method stops if one of the callbacks/listeners returns bool false

getDirtyState()

public function getDirtyState(): int;

Returns one of the DIRTY_STATE_* constants telling if the record exists in the database or not

getMessages()

public function getMessages(): MessageInterface[];

Returns array of validation messages

getModelsMetaData()

public function getModelsMetaData(): MetaDataInterface;

Returns the models meta-data service related to the entity instance.

getOperationMade()

public function getOperationMade(): int;

Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants

getReadConnection()

public function getReadConnection(): AdapterInterface;

Gets internal database connection

getReadConnectionService()

public function getReadConnectionService(): string;

Returns DependencyInjection connection service used to read data

getRelated()

public function getRelated(
    string $alias,
    mixed $arguments = null
);

Returns related records based on defined relations

getSchema()

public function getSchema(): string|null;

Returns schema name where table mapped is located

getSource()

public function getSource(): string;

Returns table name mapped in the model

getWriteConnection()

public function getWriteConnection(): AdapterInterface;

Gets internal database connection

getWriteConnectionService()

public function getWriteConnectionService(): string;

Returns DependencyInjection connection service used to write data

maximum()

public static function maximum( mixed $parameters = null ): mixed;

Allows to get the maximum value of a column that match the specified conditions

minimum()

public static function minimum( mixed $parameters = null ): mixed;

Allows to get the minimum value of a column that match the specified conditions

query()

public static function query( DiInterface $container = null ): CriteriaInterface;

Create a criteria for a specific model

refresh()

public function refresh(): ModelInterface;

Refreshes the model attributes re-querying the record from the database

save()

public function save(): bool;

Inserts or updates a model instance. Returning true on success or false otherwise.

setConnectionService()

public function setConnectionService( string $connectionService ): void;

Sets both read/write connection services

setDirtyState()

public function setDirtyState( int $dirtyState ): ModelInterface|bool;

Sets the dirty state of the object using one of the DIRTY_STATE_* constants

setReadConnectionService()

public function setReadConnectionService( string $connectionService ): void;

Sets the DependencyInjection connection service used to read data

setSnapshotData()

public function setSnapshotData(
    array $data,
    mixed $columnMap = null
): void;

Sets the record's snapshot data. This method is used internally to set snapshot data when the model was set up to keep snapshot data

setSync()

public function setSync(
    mixed $elements = null,
    bool $enabled = true
): ModelInterface;

Marks one or more many-to-many relationships to be synchronized (or not) on the next save() call.

setTransaction()

public function setTransaction( TransactionInterface $transaction ): ModelInterface;

Sets a transaction related to the Model instance

setWriteConnectionService()

public function setWriteConnectionService( string $connectionService ): void;

Sets the DependencyInjection connection service used to write data

skipOperation()

public function skipOperation( bool $skip ): void;

Skips the current operation forcing a success state

sum()

public static function sum( mixed $parameters = null ): double|ResultsetInterface;

Allows to calculate a sum on a column that match the specified conditions

update()

public function update(): bool;

Updates a model instance. If the instance does not exist in the persistence it will throw an exception. Returning true on success or false otherwise.

validationHasFailed()

public function validationHasFailed(): bool;

Check whether validation process has generated any messages

Mvc\Model\Behavior

Abstract Source on GitHub

Phalcon\Mvc\Model\Behavior

This is an optional base class for ORM behaviors

Uses Phalcon\Mvc\ModelInterface

Method Summary

Properties

protected array $options

Methods

Public · 3

__construct()

public function __construct( array $options = [] );

Phalcon\Mvc\Model\Behavior

missingMethod()

public function missingMethod(
    ModelInterface $model,
    string $method,
    array $arguments = []
);

Acts as fallbacks when a missing method is called on the model

notify()

public function notify(
    string $type,
    ModelInterface $model
);

This method receives the notifications from the EventsManager

Protected · 2

getOptions()

protected function getOptions( string $eventName = null );

Returns the behavior options related to an event

mustTakeAction()

protected function mustTakeAction( string $eventName ): bool;

Checks whether the behavior must take action on certain event

Mvc\Model\BehaviorInterface

Interface Source on GitHub

Phalcon\Mvc\Model\BehaviorInterface

Interface for Phalcon\Mvc\Model\Behavior

  • Phalcon\Mvc\Model\BehaviorInterface

Uses Phalcon\Mvc\ModelInterface

Method Summary

Methods

Public · 2

missingMethod()

public function missingMethod(
    ModelInterface $model,
    string $method,
    array $arguments = []
);

Calls a method when it's missing in the model

notify()

public function notify(
    string $type,
    ModelInterface $model
);

This method receives the notifications from the EventsManager

Mvc\Model\Behavior\Exceptions\MissingRequiredOption

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $option );

Mvc\Model\Behavior\SoftDelete

Class Source on GitHub

Phalcon\Mvc\Model\Behavior\SoftDelete

Instead of permanently delete a record it marks the record as deleted changing the value of a flag column

Uses Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Behavior · Phalcon\Mvc\Model\Behavior\Exceptions\MissingRequiredOption · Phalcon\Mvc\Model\Exception · Phalcon\Support\Settings

Method Summary

Methods

Public · 1

notify()

public function notify(
    string $type,
    ModelInterface $model
);

Listens for notifications from the models manager

Mvc\Model\Behavior\Timestampable

Class Source on GitHub

Phalcon\Mvc\Model\Behavior\Timestampable

Allows to automatically update a model’s attribute saving the datetime when a record is created or updated

Uses Closure · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Behavior · Phalcon\Mvc\Model\Behavior\Exceptions\MissingRequiredOption · Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

notify()

public function notify(
    string $type,
    ModelInterface $model
);

Listens for notifications from the models manager

Mvc\Model\Binder

Class Source on GitHub

Phalcon\Mvc\Model\Binder

This is an class for binding models into params for handler

Uses Closure · Phalcon\Cache\Adapter\AdapterInterface · Phalcon\Mvc\Controller\BindModelInterface · Phalcon\Mvc\Model\Binder\BindableInterface · Phalcon\Mvc\Model\Exceptions\HandlerMustImplementBindable · Phalcon\Mvc\Model\Exceptions\InvalidGetModelNameReturn · Phalcon\Mvc\Model\Exceptions\MissingMethodName · Phalcon\Mvc\Model\Exceptions\MissingModelClassName · ReflectionFunction · ReflectionMethod · ReflectionNamedType

Method Summary

Properties

protected array $boundModels = [] Array for storing active bound models
protected AdapterInterface|null $cache Cache object used for caching parameters for model binding
protected array $internalCache = [] Internal cache for caching parameters for model binding during request
protected array $originalValues = [] Array for original values

Methods

Public · 6

__construct()

public function __construct( AdapterInterface $cache = null );

Phalcon\Mvc\Model\Binder constructor

bindToHandler()

public function bindToHandler(
    object $handler,
    array $params,
    string $cacheKey,
    string $methodName = null
): array;

Bind models into params in proper handler

getBoundModels()

public function getBoundModels(): array;

Return the active bound models

getCache()

public function getCache(): AdapterInterface;

Sets cache instance

getOriginalValues()

public function getOriginalValues(): array;

Return the array for original values

setCache()

public function setCache( AdapterInterface $cache ): BinderInterface;

Gets cache instance

Protected · 3

findBoundModel()

protected function findBoundModel(
    mixed $paramValue,
    string $className
): mixed|bool;

Find the model by param value.

getParamsFromCache()

protected function getParamsFromCache( string $cacheKey ): array|null;

Get params classes from cache by key

getParamsFromReflection()

protected function getParamsFromReflection(
    object $handler,
    array $params,
    string $cacheKey,
    string $methodName
): array;

Get modified params for handler using reflection

Mvc\Model\BinderInterface

Interface Source on GitHub

Phalcon\Mvc\Model\BinderInterface

Interface for Phalcon\Mvc\Model\Binder

  • Phalcon\Mvc\Model\BinderInterface

Uses Phalcon\Cache\Adapter\AdapterInterface

Method Summary

Methods

Public · 4

bindToHandler()

public function bindToHandler(
    object $handler,
    array $params,
    string $cacheKey,
    string $methodName = null
): array;

Bind models into params in proper handler

getBoundModels()

public function getBoundModels(): array;

Gets active bound models

getCache()

public function getCache(): AdapterInterface;

Gets cache instance

setCache()

public function setCache( AdapterInterface $cache ): BinderInterface;

Sets cache instance

Mvc\Model\Binder\BindableInterface

Interface Source on GitHub

Phalcon\Mvc\Model\Binder\BindableInterface

Interface for bindable classes

  • Phalcon\Mvc\Model\Binder\BindableInterface

Method Summary

Methods

Public · 1

getModelName()

public function getModelName(): string|array;

Return the model name or models names and parameters keys associated with this class

Mvc\Model\Criteria

Class Source on GitHub

This class is used to build the array parameter required by Phalcon\Mvc\Model::find() and Phalcon\Mvc\Model::findFirst() using an object-oriented interface.

<?php

$invoices = Invoices::query()
    ->where("inv_cst_id = :customerId:")
    ->andWhere("inv_created_date < '2000-01-01'")
    ->bind(["customerId" => 1])
    ->limit(5, 10)
    ->orderBy("inv_title")
    ->execute();

Uses Phalcon\Db\Column · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\Model\Exceptions\InvalidModelName · Phalcon\Mvc\Model\Query\BuilderInterface

Method Summary

public CriteriaInterface andWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an AND operator public CriteriaInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a BETWEEN condition to the current conditions public CriteriaInterface bind(array $bindParams,bool $merge = false) Sets the bound parameters in the criteria public CriteriaInterface bindTypes( array $bindTypes ) Sets the bind types in the criteria public CriteriaInterface cache( array $cache ) Sets the cache options in the criteria public CriteriaInterface columns( mixed $columns ) Sets the columns to be queried. The columns can be either a string or public CriteriaInterface conditions( string $conditions ) Adds the conditions parameter to the criteria public BuilderInterface createBuilder() Creates a query builder from criteria. public CriteriaInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public ResultsetInterface execute() Executes a find using the parameters built with the criteria public CriteriaInterface forUpdate( bool $forUpdate = true ) Adds the "for_update" parameter to the criteria public CriteriaInterface fromInput(DiInterface $container,string $modelName,array $data,string $operator = "AND") Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST public string|array|null getColumns() Returns the columns to be queried public string|null getConditions() Returns the conditions parameter in the criteria public DiInterface getDI() Returns the DependencyInjector container public getGroupBy() Returns the group clause in the criteria public getHaving() Returns the having clause in the criteria public int|array|null getLimit() Returns the limit parameter in the criteria, which will be public string getModelName() Returns an internal model name on which the criteria will be applied public string|null getOrderBy() Returns the order clause in the criteria public array getParams() Returns all the parameters defined in the criteria public string|null getWhere() Returns the conditions parameter in the criteria public CriteriaInterface groupBy( mixed $group ) Adds the group-by clause to the criteria public CriteriaInterface having( mixed $having ) Adds the having clause to the criteria public CriteriaInterface inWhere(string $expr,array $values) Appends an IN condition to the current conditions public CriteriaInterface innerJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds an INNER join to the query public CriteriaInterface join(string $model,mixed $conditions = null,mixed $alias = null,mixed $type = null) Adds an INNER join to the query public CriteriaInterface leftJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a LEFT join to the query public CriteriaInterface limit(int $limit,int $offset = 0) Adds the limit parameter to the criteria. public CriteriaInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a NOT BETWEEN condition to the current conditions public CriteriaInterface notInWhere(string $expr,array $values) Appends a NOT IN condition to the current conditions public CriteriaInterface orWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an OR operator public CriteriaInterface orderBy( string $orderColumns ) Adds the order-by clause to the criteria public CriteriaInterface rightJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a RIGHT join to the query public void setDI( DiInterface $container ) Sets the DependencyInjector container public CriteriaInterface setModelName( string $modelName ) Set a model on which the query will be executed public CriteriaInterface sharedLock( bool $sharedLock = true ) Adds the "shared_lock" parameter to the criteria public CriteriaInterface where(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Sets the conditions parameter in the criteria

Properties

protected array $bindParams
protected array $bindTypes
protected int $hiddenParamNumber = 0
protected string|null $model = null
protected array $params = []

Methods

Public · 38

andWhere()

public function andWhere(
    string $conditions,
    mixed $bindParams = null,
    mixed $bindTypes = null
): CriteriaInterface;

Appends a condition to the current conditions using an AND operator

betweenWhere()

public function betweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum
): CriteriaInterface;

Appends a BETWEEN condition to the current conditions

$criteria->betweenWhere("price", 100.25, 200.50);

bind()

public function bind(
    array $bindParams,
    bool $merge = false
): CriteriaInterface;

Sets the bound parameters in the criteria This method replaces all previously set bound parameters

bindTypes()

public function bindTypes( array $bindTypes ): CriteriaInterface;

Sets the bind types in the criteria This method replaces all previously set bound parameters

cache()

public function cache( array $cache ): CriteriaInterface;

Sets the cache options in the criteria This method replaces all previously set cache options

columns()

public function columns( mixed $columns ): CriteriaInterface;

Sets the columns to be queried. The columns can be either a string or an array of strings. If the argument is a (single, non-embedded) string, its content can specify one or more columns, separated by commas, the same way that one uses the SQL select statement. You can use aliases, aggregate functions, etc. If you need to reference other models you will need to reference them with their namespaces.

When using an array as a parameter, you will need to specify one field per array element. If a non-numeric key is defined in the array, it will be used as the alias in the query

<?php

// String, comma separated values
$criteria->columns("id, category");

// Array, one column per element
$criteria->columns(
    [
        "inv_id",
        "inv_total",
    ]
);

// Array with named key. The name of the key acts as an
// alias (`AS` clause)
$criteria->columns(
    [
        "inv_cst_id",
        "total_invoices" => "COUNT(*)",
    ]
);

// Different models
$criteria->columns(
    [
        "\Phalcon\Models\Invoices.*",
        "\Phalcon\Models\Customers.cst_name_first",
        "\Phalcon\Models\Customers.cst_name_last",
    ]
);

conditions()

public function conditions( string $conditions ): CriteriaInterface;

Adds the conditions parameter to the criteria

createBuilder()

public function createBuilder(): BuilderInterface;

Creates a query builder from criteria.

where("inv_cst_id = :customerId:") ->bind(["customerId" => 1]) ->createBuilder();
#### `distinct()` { #mvcmodelcriteria-distinct }

```php
public function distinct( mixed $distinct ): CriteriaInterface;
Sets SELECT DISTINCT / SELECT ALL flag #### `execute()` { #mvcmodelcriteria-execute }
public function execute(): ResultsetInterface;
Executes a find using the parameters built with the criteria #### `forUpdate()` { #mvcmodelcriteria-forupdate }
public function forUpdate( bool $forUpdate = true ): CriteriaInterface;
Adds the "for_update" parameter to the criteria #### `fromInput()` { #mvcmodelcriteria-frominput }
public static function fromInput(
    DiInterface $container,
    string $modelName,
    array $data,
    string $operator = "AND"
): CriteriaInterface;
Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST #### `getColumns()` { #mvcmodelcriteria-getcolumns }
public function getColumns(): string|array|null;
Returns the columns to be queried #### `getConditions()` { #mvcmodelcriteria-getconditions }
public function getConditions(): string|null;
Returns the conditions parameter in the criteria #### `getDI()` { #mvcmodelcriteria-getdi }
public function getDI(): DiInterface;
Returns the DependencyInjector container #### `getGroupBy()` { #mvcmodelcriteria-getgroupby }
public function getGroupBy();
Returns the group clause in the criteria #### `getHaving()` { #mvcmodelcriteria-gethaving }
public function getHaving();
Returns the having clause in the criteria #### `getLimit()` { #mvcmodelcriteria-getlimit }
public function getLimit(): int|array|null;
Returns the limit parameter in the criteria, which will be - An integer if 'limit' was set without an 'offset' - An array with 'number' and 'offset' keys if an offset was set with the limit - NULL if limit has not been set #### `getModelName()` { #mvcmodelcriteria-getmodelname }
public function getModelName(): string;
Returns an internal model name on which the criteria will be applied #### `getOrderBy()` { #mvcmodelcriteria-getorderby }
public function getOrderBy(): string|null;
Returns the order clause in the criteria #### `getParams()` { #mvcmodelcriteria-getparams }
public function getParams(): array;
Returns all the parameters defined in the criteria #### `getWhere()` { #mvcmodelcriteria-getwhere }
public function getWhere(): string|null;
Returns the conditions parameter in the criteria #### `groupBy()` { #mvcmodelcriteria-groupby }
public function groupBy( mixed $group ): CriteriaInterface;
Adds the group-by clause to the criteria #### `having()` { #mvcmodelcriteria-having }
public function having( mixed $having ): CriteriaInterface;
Adds the having clause to the criteria #### `inWhere()` { #mvcmodelcriteria-inwhere }
public function inWhere(
    string $expr,
    array $values
): CriteriaInterface;
Appends an IN condition to the current conditions
$criteria->inWhere("id", [1, 2, 3]);
#### `innerJoin()` { #mvcmodelcriteria-innerjoin }
public function innerJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;
Adds an INNER join to the query
<?php

$criteria->innerJoin(
    Invoices::class
);

$criteria->innerJoin(
    Invoices::class,
    "inv_cst_id = Customers.cst_id"
);

$criteria->innerJoin(
    Invoices::class,
    "i.inv_cst_id = Customers.cst_id",
    "i"
);
#### `join()` { #mvcmodelcriteria-join }
public function join(
    string $model,
    mixed $conditions = null,
    mixed $alias = null,
    mixed $type = null
): CriteriaInterface;
Adds an INNER join to the query
<?php

$criteria->join(
    Invoices::class
);

$criteria->join(
    Invoices::class,
    "inv_cst_id = Customers.cst_id"
);

$criteria->join(
    Invoices::class,
    "i.inv_cst_id = Customers.cst_id",
    "i"
);

$criteria->join(
    Invoices::class,
    "i.inv_cst_id = Customers.cst_id",
    "i",
    "LEFT"
);
#### `leftJoin()` { #mvcmodelcriteria-leftjoin }
public function leftJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;
Adds a LEFT join to the query
<?php

$criteria->leftJoin(
    Invoices::class,
    "i.inv_cst_id = Customers.cst_id",
    "i"
);
#### `limit()` { #mvcmodelcriteria-limit }
public function limit(
    int $limit,
    int $offset = 0
): CriteriaInterface;
Adds the limit parameter to the criteria.
$criteria->limit(100);
$criteria->limit(100, 200);
$criteria->limit("100", "200");
#### `notBetweenWhere()` { #mvcmodelcriteria-notbetweenwhere }
public function notBetweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum
): CriteriaInterface;
Appends a NOT BETWEEN condition to the current conditions
$criteria->notBetweenWhere("price", 100.25, 200.50);
#### `notInWhere()` { #mvcmodelcriteria-notinwhere }
public function notInWhere(
    string $expr,
    array $values
): CriteriaInterface;
Appends a NOT IN condition to the current conditions
$criteria->notInWhere("id", [1, 2, 3]);
#### `orWhere()` { #mvcmodelcriteria-orwhere }
public function orWhere(
    string $conditions,
    mixed $bindParams = null,
    mixed $bindTypes = null
): CriteriaInterface;
Appends a condition to the current conditions using an OR operator #### `orderBy()` { #mvcmodelcriteria-orderby }
public function orderBy( string $orderColumns ): CriteriaInterface;
Adds the order-by clause to the criteria #### `rightJoin()` { #mvcmodelcriteria-rightjoin }
public function rightJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;
Adds a RIGHT join to the query
<?php

$criteria->rightJoin(
    Invoices::class,
    "i.inv_cst_id = Customers.cst_id",
    "i"
);
#### `setDI()` { #mvcmodelcriteria-setdi }
public function setDI( DiInterface $container ): void;
Sets the DependencyInjector container #### `setModelName()` { #mvcmodelcriteria-setmodelname }
public function setModelName( string $modelName ): CriteriaInterface;
Set a model on which the query will be executed #### `sharedLock()` { #mvcmodelcriteria-sharedlock }
public function sharedLock( bool $sharedLock = true ): CriteriaInterface;
Adds the "shared_lock" parameter to the criteria #### `where()` { #mvcmodelcriteria-where }
public function where(
    string $conditions,
    mixed $bindParams = null,
    mixed $bindTypes = null
): CriteriaInterface;
Sets the conditions parameter in the criteria ## Mvc\Model\CriteriaInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/CriteriaInterface.zep){ .src-btn } Phalcon\Mvc\Model\CriteriaInterface Interface for Phalcon\Mvc\Model\Criteria
- **`Phalcon\Mvc\Model\CriteriaInterface`**
__Uses__ `Phalcon\Di\DiInterface` { .api-uses } ### Method Summary
public CriteriaInterface andWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an AND operator public CriteriaInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a BETWEEN condition to the current conditions public CriteriaInterface bind( array $bindParams ) Sets the bound parameters in the criteria public CriteriaInterface bindTypes( array $bindTypes ) Sets the bind types in the criteria public CriteriaInterface cache( array $cache ) Sets the cache options in the criteria public CriteriaInterface conditions( string $conditions ) Adds the conditions parameter to the criteria public CriteriaInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public ResultsetInterface execute() Executes a find using the parameters built with the criteria public CriteriaInterface forUpdate( bool $forUpdate = true ) Sets the "for_update" parameter to the criteria public string|array|null getColumns() Returns the columns to be queried public string|null getConditions() Returns the conditions parameter in the criteria public getGroupBy() Returns the group clause in the criteria public getHaving() Returns the having clause in the criteria public int|array|null getLimit() Returns the limit parameter in the criteria, which will be public string getModelName() Returns an internal model name on which the criteria will be applied public string|null getOrderBy() Returns the order parameter in the criteria public array getParams() Returns all the parameters defined in the criteria public string|null getWhere() Returns the conditions parameter in the criteria public CriteriaInterface groupBy( mixed $group ) Adds the group-by clause to the criteria public CriteriaInterface having( mixed $having ) Adds the having clause to the criteria public CriteriaInterface inWhere(string $expr,array $values) Appends an IN condition to the current conditions public CriteriaInterface innerJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds an INNER join to the query public CriteriaInterface leftJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a LEFT join to the query public CriteriaInterface limit(int $limit,int $offset = 0) Sets the limit parameter to the criteria public CriteriaInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a NOT BETWEEN condition to the current conditions public CriteriaInterface notInWhere(string $expr,array $values) Appends a NOT IN condition to the current conditions public CriteriaInterface orWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an OR operator public CriteriaInterface orderBy( string $orderColumns ) Adds the order-by parameter to the criteria public CriteriaInterface rightJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a RIGHT join to the query public CriteriaInterface setModelName( string $modelName ) Set a model on which the query will be executed public CriteriaInterface sharedLock( bool $sharedLock = true ) Sets the "shared_lock" parameter to the criteria public CriteriaInterface where(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Sets the conditions parameter in the criteria
### Methods
Public · 32
#### `andWhere()` { #mvcmodelcriteriainterface-andwhere }
public function andWhere(
    string $conditions,
    mixed $bindParams = null,
    mixed $bindTypes = null
): CriteriaInterface;
Appends a condition to the current conditions using an AND operator #### `betweenWhere()` { #mvcmodelcriteriainterface-betweenwhere }
public function betweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum
): CriteriaInterface;
Appends a BETWEEN condition to the current conditions
$criteria->betweenWhere("price", 100.25, 200.50);
#### `bind()` { #mvcmodelcriteriainterface-bind }
public function bind( array $bindParams ): CriteriaInterface;
Sets the bound parameters in the criteria This method replaces all previously set bound parameters #### `bindTypes()` { #mvcmodelcriteriainterface-bindtypes }
public function bindTypes( array $bindTypes ): CriteriaInterface;
Sets the bind types in the criteria This method replaces all previously set bound parameters #### `cache()` { #mvcmodelcriteriainterface-cache }
public function cache( array $cache ): CriteriaInterface;
Sets the cache options in the criteria This method replaces all previously set cache options #### `conditions()` { #mvcmodelcriteriainterface-conditions }
public function conditions( string $conditions ): CriteriaInterface;
Adds the conditions parameter to the criteria #### `distinct()` { #mvcmodelcriteriainterface-distinct }
public function distinct( mixed $distinct ): CriteriaInterface;
Sets SELECT DISTINCT / SELECT ALL flag #### `execute()` { #mvcmodelcriteriainterface-execute }
public function execute(): ResultsetInterface;
Executes a find using the parameters built with the criteria #### `forUpdate()` { #mvcmodelcriteriainterface-forupdate }
public function forUpdate( bool $forUpdate = true ): CriteriaInterface;
Sets the "for_update" parameter to the criteria #### `getColumns()` { #mvcmodelcriteriainterface-getcolumns }
public function getColumns(): string|array|null;
Returns the columns to be queried #### `getConditions()` { #mvcmodelcriteriainterface-getconditions }
public function getConditions(): string|null;
Returns the conditions parameter in the criteria #### `getGroupBy()` { #mvcmodelcriteriainterface-getgroupby }
public function getGroupBy();
Returns the group clause in the criteria #### `getHaving()` { #mvcmodelcriteriainterface-gethaving }
public function getHaving();
Returns the having clause in the criteria #### `getLimit()` { #mvcmodelcriteriainterface-getlimit }
public function getLimit(): int|array|null;
Returns the limit parameter in the criteria, which will be - An integer if 'limit' was set without an 'offset' - An array with 'number' and 'offset' keys if an offset was set with the limit - NULL if limit has not been set #### `getModelName()` { #mvcmodelcriteriainterface-getmodelname }
public function getModelName(): string;
Returns an internal model name on which the criteria will be applied #### `getOrderBy()` { #mvcmodelcriteriainterface-getorderby }
public function getOrderBy(): string|null;
Returns the order parameter in the criteria #### `getParams()` { #mvcmodelcriteriainterface-getparams }
public function getParams(): array;
Returns all the parameters defined in the criteria #### `getWhere()` { #mvcmodelcriteriainterface-getwhere }
public function getWhere(): string|null;
Returns the conditions parameter in the criteria #### `groupBy()` { #mvcmodelcriteriainterface-groupby }
public function groupBy( mixed $group ): CriteriaInterface;
Adds the group-by clause to the criteria #### `having()` { #mvcmodelcriteriainterface-having }
public function having( mixed $having ): CriteriaInterface;
Adds the having clause to the criteria #### `inWhere()` { #mvcmodelcriteriainterface-inwhere }
public function inWhere(
    string $expr,
    array $values
): CriteriaInterface;
Appends an IN condition to the current conditions
$criteria->inWhere("id", [1, 2, 3]);
#### `innerJoin()` { #mvcmodelcriteriainterface-innerjoin }
public function innerJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;
Adds an INNER join to the query
$criteria->innerJoin(
    Robots::class
);

$criteria->innerJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id"
);

$criteria->innerJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);
#### `leftJoin()` { #mvcmodelcriteriainterface-leftjoin }
public function leftJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;
Adds a LEFT join to the query
$criteria->leftJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);
#### `limit()` { #mvcmodelcriteriainterface-limit }
public function limit(
    int $limit,
    int $offset = 0
): CriteriaInterface;
Sets the limit parameter to the criteria #### `notBetweenWhere()` { #mvcmodelcriteriainterface-notbetweenwhere }
public function notBetweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum
): CriteriaInterface;
Appends a NOT BETWEEN condition to the current conditions
$criteria->notBetweenWhere("price", 100.25, 200.50);
#### `notInWhere()` { #mvcmodelcriteriainterface-notinwhere }
public function notInWhere(
    string $expr,
    array $values
): CriteriaInterface;
Appends a NOT IN condition to the current conditions
$criteria->notInWhere("id", [1, 2, 3]);
#### `orWhere()` { #mvcmodelcriteriainterface-orwhere }
public function orWhere(
    string $conditions,
    mixed $bindParams = null,
    mixed $bindTypes = null
): CriteriaInterface;
Appends a condition to the current conditions using an OR operator #### `orderBy()` { #mvcmodelcriteriainterface-orderby }
public function orderBy( string $orderColumns ): CriteriaInterface;
Adds the order-by parameter to the criteria #### `rightJoin()` { #mvcmodelcriteriainterface-rightjoin }
public function rightJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;
Adds a RIGHT join to the query
$criteria->rightJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);
#### `setModelName()` { #mvcmodelcriteriainterface-setmodelname }
public function setModelName( string $modelName ): CriteriaInterface;
Set a model on which the query will be executed #### `sharedLock()` { #mvcmodelcriteriainterface-sharedlock }
public function sharedLock( bool $sharedLock = true ): CriteriaInterface;
Sets the "shared_lock" parameter to the criteria #### `where()` { #mvcmodelcriteriainterface-where }
public function where(
    string $conditions,
    mixed $bindParams = null,
    mixed $bindTypes = null
): CriteriaInterface;
Sets the conditions parameter in the criteria ## Mvc\Model\Exception Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exception.zep){ .src-btn } Phalcon\Mvc\Model\Exception Exceptions thrown in Phalcon\Mvc\Model\* classes will use this class
- `\Exception` - **`Phalcon\Mvc\Model\Exception`** - [`Phalcon\Mvc\Model\Behavior\Exceptions\MissingRequiredOption`](#mvcmodelbehaviorexceptionsmissingrequiredoption) - [`Phalcon\Mvc\Model\Exceptions\BelongsToRequiresObject`](#mvcmodelexceptionsbelongstorequiresobject) - [`Phalcon\Mvc\Model\Exceptions\BindTypeNotDefined`](#mvcmodelexceptionsbindtypenotdefined) - [`Phalcon\Mvc\Model\Exceptions\CannotResolveAttribute`](#mvcmodelexceptionscannotresolveattribute) - [`Phalcon\Mvc\Model\Exceptions\ColumnNotInMap`](#mvcmodelexceptionscolumnnotinmap) - [`Phalcon\Mvc\Model\Exceptions\ColumnNotInTableColumns`](#mvcmodelexceptionscolumnnotintablecolumns) - [`Phalcon\Mvc\Model\Exceptions\ColumnNotInTableMap`](#mvcmodelexceptionscolumnnotintablemap) - [`Phalcon\Mvc\Model\Exceptions\CorruptColumnType`](#mvcmodelexceptionscorruptcolumntype) - [`Phalcon\Mvc\Model\Exceptions\CursorIsImmutable`](#mvcmodelexceptionscursorisimmutable) - [`Phalcon\Mvc\Model\Exceptions\DataTypeNotDefined`](#mvcmodelexceptionsdatatypenotdefined) - [`Phalcon\Mvc\Model\Exceptions\HandlerMustImplementBindable`](#mvcmodelexceptionshandlermustimplementbindable) - [`Phalcon\Mvc\Model\Exceptions\IdentityNotInColumnMap`](#mvcmodelexceptionsidentitynotincolumnmap) - [`Phalcon\Mvc\Model\Exceptions\IdentityNotInTableColumns`](#mvcmodelexceptionsidentitynotintablecolumns) - [`Phalcon\Mvc\Model\Exceptions\IndexNotInCursor`](#mvcmodelexceptionsindexnotincursor) - [`Phalcon\Mvc\Model\Exceptions\IndexNotInRow`](#mvcmodelexceptionsindexnotinrow) - [`Phalcon\Mvc\Model\Exceptions\InvalidConnectionService`](#mvcmodelexceptionsinvalidconnectionservice) - [`Phalcon\Mvc\Model\Exceptions\InvalidContainer`](#mvcmodelexceptionsinvalidcontainer) - [`Phalcon\Mvc\Model\Exceptions\InvalidDumpResultKey`](#mvcmodelexceptionsinvaliddumpresultkey) - [`Phalcon\Mvc\Model\Exceptions\InvalidFindParameters`](#mvcmodelexceptionsinvalidfindparameters) - [`Phalcon\Mvc\Model\Exceptions\InvalidGetModelNameReturn`](#mvcmodelexceptionsinvalidgetmodelnamereturn) - [`Phalcon\Mvc\Model\Exceptions\InvalidModelName`](#mvcmodelexceptionsinvalidmodelname) - [`Phalcon\Mvc\Model\Exceptions\InvalidModelsManagerService`](#mvcmodelexceptionsinvalidmodelsmanagerservice) - [`Phalcon\Mvc\Model\Exceptions\InvalidModelsMetadataService`](#mvcmodelexceptionsinvalidmodelsmetadataservice) - [`Phalcon\Mvc\Model\Exceptions\InvalidResultsetCacheService`](#mvcmodelexceptionsinvalidresultsetcacheservice) - [`Phalcon\Mvc\Model\Exceptions\InvalidReturnedRecord`](#mvcmodelexceptionsinvalidreturnedrecord) - [`Phalcon\Mvc\Model\Exceptions\InvalidSerializationData`](#mvcmodelexceptionsinvalidserializationdata) - [`Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable`](#mvcmodelexceptionsmanagerormservicesunavailable) - [`Phalcon\Mvc\Model\Exceptions\MethodNotFound`](#mvcmodelexceptionsmethodnotfound) - [`Phalcon\Mvc\Model\Exceptions\MissingMethodName`](#mvcmodelexceptionsmissingmethodname) - [`Phalcon\Mvc\Model\Exceptions\MissingModelClassName`](#mvcmodelexceptionsmissingmodelclassname) - [`Phalcon\Mvc\Model\Exceptions\ModelCouldNotLoad`](#mvcmodelexceptionsmodelcouldnotload) - [`Phalcon\Mvc\Model\Exceptions\ModelOrmServicesUnavailable`](#mvcmodelexceptionsmodelormservicesunavailable) - [`Phalcon\Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet`](#mvcmodelexceptionsprimarykeyattributenotset) - [`Phalcon\Mvc\Model\Exceptions\PrimaryKeyRequired`](#mvcmodelexceptionsprimarykeyrequired) - [`Phalcon\Mvc\Model\Exceptions\PropertyNotAccessible`](#mvcmodelexceptionspropertynotaccessible) - [`Phalcon\Mvc\Model\Exceptions\RecordCannotRefresh`](#mvcmodelexceptionsrecordcannotrefresh) - [`Phalcon\Mvc\Model\Exceptions\RecordNotPersisted`](#mvcmodelexceptionsrecordnotpersisted) - [`Phalcon\Mvc\Model\Exceptions\ReferencedFieldsMismatch`](#mvcmodelexceptionsreferencedfieldsmismatch) - [`Phalcon\Mvc\Model\Exceptions\RelationAliasMustBeString`](#mvcmodelexceptionsrelationaliasmustbestring) - [`Phalcon\Mvc\Model\Exceptions\RelationNotDefined`](#mvcmodelexceptionsrelationnotdefined) - [`Phalcon\Mvc\Model\Exceptions\RelationRequiresObjectOrArray`](#mvcmodelexceptionsrelationrequiresobjectorarray) - [`Phalcon\Mvc\Model\Exceptions\ResultsetColumnNotInMap`](#mvcmodelexceptionsresultsetcolumnnotinmap) - [`Phalcon\Mvc\Model\Exceptions\RowIsImmutable`](#mvcmodelexceptionsrowisimmutable) - [`Phalcon\Mvc\Model\Exceptions\SnapshotsDisabled`](#mvcmodelexceptionssnapshotsdisabled) - [`Phalcon\Mvc\Model\Exceptions\StaticMethodRequiresOneArgument`](#mvcmodelexceptionsstaticmethodrequiresoneargument) - [`Phalcon\Mvc\Model\Exceptions\UnknownRelationType`](#mvcmodelexceptionsunknownrelationtype) - [`Phalcon\Mvc\Model\Exceptions\UpdateSnapshotDisabled`](#mvcmodelexceptionsupdatesnapshotdisabled) - [`Phalcon\Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns`](#mvcmodelmetadataexceptionscannotobtaintablecolumns) - [`Phalcon\Mvc\Model\MetaData\Exceptions\ColumnMapNotArray`](#mvcmodelmetadataexceptionscolumnmapnotarray) - [`Phalcon\Mvc\Model\MetaData\Exceptions\ContainerRequired`](#mvcmodelmetadataexceptionscontainerrequired) - [`Phalcon\Mvc\Model\MetaData\Exceptions\CorruptedMetaData`](#mvcmodelmetadataexceptionscorruptedmetadata) - [`Phalcon\Mvc\Model\MetaData\Exceptions\InvalidContainer`](#mvcmodelmetadataexceptionsinvalidcontainer) - [`Phalcon\Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel`](#mvcmodelmetadataexceptionsinvalidmetadataformodel) - [`Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable`](#mvcmodelmetadataexceptionsmetadatadirectorynotwritable) - [`Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed`](#mvcmodelmetadataexceptionsmetadatastrategyfailed) - [`Phalcon\Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass`](#mvcmodelmetadataexceptionsnoannotationsforclass) - [`Phalcon\Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass`](#mvcmodelmetadataexceptionsnopropertyannotationsforclass) - [`Phalcon\Mvc\Model\MetaData\Exceptions\TableNotInDatabase`](#mvcmodelmetadataexceptionstablenotindatabase) - [`Phalcon\Mvc\Model\Query\Exceptions\AmbiguousColumn`](#mvcmodelqueryexceptionsambiguouscolumn) - [`Phalcon\Mvc\Model\Query\Exceptions\AmbiguousJoinRelation`](#mvcmodelqueryexceptionsambiguousjoinrelation) - [`Phalcon\Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders`](#mvcmodelqueryexceptionsbindparameternotinplaceholders) - [`Phalcon\Mvc\Model\Query\Exceptions\BindTypeRequiresArray`](#mvcmodelqueryexceptionsbindtyperequiresarray) - [`Phalcon\Mvc\Model\Query\Exceptions\BindValueRequired`](#mvcmodelqueryexceptionsbindvaluerequired) - [`Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap`](#mvcmodelqueryexceptionsbuilderbuildercolumnnotinmap) - [`Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid`](#mvcmodelqueryexceptionsbuilderbuilderconditioninvalid) - [`Phalcon\Mvc\Model\Query\Exceptions\Builder\ModelRequired`](#mvcmodelqueryexceptionsbuildermodelrequired) - [`Phalcon\Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey`](#mvcmodelqueryexceptionsbuildernoprimarykey) - [`Phalcon\Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable`](#mvcmodelqueryexceptionsbuilderoperatornotavailable) - [`Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInDomain`](#mvcmodelqueryexceptionscolumnnotindomain) - [`Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels`](#mvcmodelqueryexceptionscolumnnotinselectedmodels) - [`Phalcon\Mvc\Model\Query\Exceptions\CorruptedAst`](#mvcmodelqueryexceptionscorruptedast) - [`Phalcon\Mvc\Model\Query\Exceptions\CorruptedDeleteAst`](#mvcmodelqueryexceptionscorrupteddeleteast) - [`Phalcon\Mvc\Model\Query\Exceptions\CorruptedInsertAst`](#mvcmodelqueryexceptionscorruptedinsertast) - [`Phalcon\Mvc\Model\Query\Exceptions\CorruptedSelectAst`](#mvcmodelqueryexceptionscorruptedselectast) - [`Phalcon\Mvc\Model\Query\Exceptions\CorruptedUpdateAst`](#mvcmodelqueryexceptionscorruptedupdateast) - [`Phalcon\Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported`](#mvcmodelqueryexceptionsdeletemultiplenotsupported) - [`Phalcon\Mvc\Model\Query\Exceptions\DuplicateAlias`](#mvcmodelqueryexceptionsduplicatealias) - [`Phalcon\Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue`](#mvcmodelqueryexceptionsemptyarrayplaceholdervalue) - [`Phalcon\Mvc\Model\Query\Exceptions\InsertColumnCountMismatch`](#mvcmodelqueryexceptionsinsertcolumncountmismatch) - [`Phalcon\Mvc\Model\Query\Exceptions\InvalidCachedResultset`](#mvcmodelqueryexceptionsinvalidcachedresultset) - [`Phalcon\Mvc\Model\Query\Exceptions\InvalidCachingOptions`](#mvcmodelqueryexceptionsinvalidcachingoptions) - [`Phalcon\Mvc\Model\Query\Exceptions\InvalidColumnDefinition`](#mvcmodelqueryexceptionsinvalidcolumndefinition) - [`Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedManager`](#mvcmodelqueryexceptionsinvalidinjectedmanager) - [`Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedMetadata`](#mvcmodelqueryexceptionsinvalidinjectedmetadata) - [`Phalcon\Mvc\Model\Query\Exceptions\InvalidQueryCacheService`](#mvcmodelqueryexceptionsinvalidquerycacheservice) - [`Phalcon\Mvc\Model\Query\Exceptions\InvalidResultsetClass`](#mvcmodelqueryexceptionsinvalidresultsetclass) - [`Phalcon\Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed`](#mvcmodelqueryexceptionsjoinaliasalreadyused) - [`Phalcon\Mvc\Model\Query\Exceptions\JoinFieldCountMismatch`](#mvcmodelqueryexceptionsjoinfieldcountmismatch) - [`Phalcon\Mvc\Model\Query\Exceptions\MissingCacheKey`](#mvcmodelqueryexceptionsmissingcachekey) - [`Phalcon\Mvc\Model\Query\Exceptions\MissingMetaData`](#mvcmodelqueryexceptionsmissingmetadata) - [`Phalcon\Mvc\Model\Query\Exceptions\MissingModelAttribute`](#mvcmodelqueryexceptionsmissingmodelattribute) - [`Phalcon\Mvc\Model\Query\Exceptions\MissingModelsManager`](#mvcmodelqueryexceptionsmissingmodelsmanager) - [`Phalcon\Mvc\Model\Query\Exceptions\MixedDatabaseSystems`](#mvcmodelqueryexceptionsmixeddatabasesystems) - [`Phalcon\Mvc\Model\Query\Exceptions\ModelSourceNotFound`](#mvcmodelqueryexceptionsmodelsourcenotfound) - [`Phalcon\Mvc\Model\Query\Exceptions\ModelsListNotLoaded`](#mvcmodelqueryexceptionsmodelslistnotloaded) - [`Phalcon\Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported`](#mvcmodelqueryexceptionsmultiplesqlstatementsnotsupported) - [`Phalcon\Mvc\Model\Query\Exceptions\NoModelForAlias`](#mvcmodelqueryexceptionsnomodelforalias) - [`Phalcon\Mvc\Model\Query\Exceptions\PhqlColumnNotInMap`](#mvcmodelqueryexceptionsphqlcolumnnotinmap) - [`Phalcon\Mvc\Model\Query\Exceptions\ReadConnectionMissing`](#mvcmodelqueryexceptionsreadconnectionmissing) - [`Phalcon\Mvc\Model\Query\Exceptions\RelationshipNotFound`](#mvcmodelqueryexceptionsrelationshipnotfound) - [`Phalcon\Mvc\Model\Query\Exceptions\ResultsetClassNotFound`](#mvcmodelqueryexceptionsresultsetclassnotfound) - [`Phalcon\Mvc\Model\Query\Exceptions\ResultsetNonCacheable`](#mvcmodelqueryexceptionsresultsetnoncacheable) - [`Phalcon\Mvc\Model\Query\Exceptions\UnknownBindType`](#mvcmodelqueryexceptionsunknownbindtype) - [`Phalcon\Mvc\Model\Query\Exceptions\UnknownColumnType`](#mvcmodelqueryexceptionsunknowncolumntype) - [`Phalcon\Mvc\Model\Query\Exceptions\UnknownJoinType`](#mvcmodelqueryexceptionsunknownjointype) - [`Phalcon\Mvc\Model\Query\Exceptions\UnknownModelOrAlias`](#mvcmodelqueryexceptionsunknownmodeloralias) - [`Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpression`](#mvcmodelqueryexceptionsunknownphqlexpression) - [`Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType`](#mvcmodelqueryexceptionsunknownphqlexpressiontype) - [`Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlStatement`](#mvcmodelqueryexceptionsunknownphqlstatement) - [`Phalcon\Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported`](#mvcmodelqueryexceptionsupdatemultiplenotsupported) - [`Phalcon\Mvc\Model\Query\Exceptions\WriteConnectionMissing`](#mvcmodelqueryexceptionswriteconnectionmissing) - [`Phalcon\Mvc\Model\Transaction\Exception`](#mvcmodeltransactionexception) - [`Phalcon\Mvc\Model\ValidationFailed`](#mvcmodelvalidationfailed)
## Mvc\Model\Exceptions\BelongsToRequiresObject Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/BelongsToRequiresObject.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\BelongsToRequiresObject`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsbelongstorequiresobject-__construct }
public function __construct(
    string $className,
    string $relationName
);
## Mvc\Model\Exceptions\BindTypeNotDefined Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/BindTypeNotDefined.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\BindTypeNotDefined`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsbindtypenotdefined-__construct }
public function __construct(
    string $column,
    string $className
);
## Mvc\Model\Exceptions\CannotResolveAttribute Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/CannotResolveAttribute.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\CannotResolveAttribute`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionscannotresolveattribute-__construct }
public function __construct(
    string $attribute,
    string $className
);
## Mvc\Model\Exceptions\ColumnNotInMap Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ColumnNotInMap.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ColumnNotInMap`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionscolumnnotinmap-__construct }
public function __construct(
    string $column,
    string $className
);
## Mvc\Model\Exceptions\ColumnNotInTableColumns Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ColumnNotInTableColumns.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ColumnNotInTableColumns`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionscolumnnotintablecolumns-__construct }
public function __construct(
    string $column,
    string $className
);
## Mvc\Model\Exceptions\ColumnNotInTableMap Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ColumnNotInTableMap.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ColumnNotInTableMap`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionscolumnnotintablemap-__construct }
public function __construct(
    string $column,
    string $className
);
## Mvc\Model\Exceptions\CorruptColumnType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/CorruptColumnType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\CorruptColumnType`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionscorruptcolumntype-__construct }
public function __construct();
## Mvc\Model\Exceptions\CursorIsImmutable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/CursorIsImmutable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\CursorIsImmutable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionscursorisimmutable-__construct }
public function __construct();
## Mvc\Model\Exceptions\DataTypeNotDefined Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/DataTypeNotDefined.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\DataTypeNotDefined`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsdatatypenotdefined-__construct }
public function __construct(
    string $column,
    string $className
);
## Mvc\Model\Exceptions\HandlerMustImplementBindable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/HandlerMustImplementBindable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\HandlerMustImplementBindable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionshandlermustimplementbindable-__construct }
public function __construct();
## Mvc\Model\Exceptions\IdentityNotInColumnMap Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/IdentityNotInColumnMap.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\IdentityNotInColumnMap`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsidentitynotincolumnmap-__construct }
public function __construct(
    string $identityField,
    string $className
);
## Mvc\Model\Exceptions\IdentityNotInTableColumns Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/IdentityNotInTableColumns.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\IdentityNotInTableColumns`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsidentitynotintablecolumns-__construct }
public function __construct(
    string $identityField,
    string $className
);
## Mvc\Model\Exceptions\IndexNotInCursor Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/IndexNotInCursor.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\IndexNotInCursor`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsindexnotincursor-__construct }
public function __construct();
## Mvc\Model\Exceptions\IndexNotInRow Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/IndexNotInRow.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\IndexNotInRow`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsindexnotinrow-__construct }
public function __construct();
## Mvc\Model\Exceptions\InvalidConnectionService Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidConnectionService.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidConnectionService`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidconnectionservice-__construct }
public function __construct();
## Mvc\Model\Exceptions\InvalidContainer Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidContainer.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidContainer`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidcontainer-__construct }
public function __construct();
## Mvc\Model\Exceptions\InvalidDumpResultKey Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidDumpResultKey.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidDumpResultKey`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvaliddumpresultkey-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\InvalidFindParameters Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidFindParameters.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidFindParameters`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidfindparameters-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\InvalidGetModelNameReturn Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidGetModelNameReturn.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidGetModelNameReturn`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidgetmodelnamereturn-__construct }
public function __construct();
## Mvc\Model\Exceptions\InvalidModelName Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidModelName.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidModelName`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidmodelname-__construct }
public function __construct();
## Mvc\Model\Exceptions\InvalidModelsManagerService Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidModelsManagerService.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidModelsManagerService`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidmodelsmanagerservice-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\InvalidModelsMetadataService Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidModelsMetadataService.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidModelsMetadataService`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidmodelsmetadataservice-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\InvalidResultsetCacheService Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidResultsetCacheService.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidResultsetCacheService`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidresultsetcacheservice-__construct }
public function __construct();
## Mvc\Model\Exceptions\InvalidReturnedRecord Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidReturnedRecord.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidReturnedRecord`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidreturnedrecord-__construct }
public function __construct();
## Mvc\Model\Exceptions\InvalidSerializationData Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/InvalidSerializationData.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\InvalidSerializationData`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsinvalidserializationdata-__construct }
public function __construct();
## Mvc\Model\Exceptions\ManagerOrmServicesUnavailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ManagerOrmServicesUnavailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsmanagerormservicesunavailable-__construct }
public function __construct();
## Mvc\Model\Exceptions\MethodNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/MethodNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\MethodNotFound`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsmethodnotfound-__construct }
public function __construct(
    string $method,
    string $modelName
);
## Mvc\Model\Exceptions\MissingMethodName Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/MissingMethodName.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\MissingMethodName`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsmissingmethodname-__construct }
public function __construct();
## Mvc\Model\Exceptions\MissingModelClassName Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/MissingModelClassName.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\MissingModelClassName`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsmissingmodelclassname-__construct }
public function __construct( string $paramKey );
## Mvc\Model\Exceptions\ModelCouldNotLoad Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ModelCouldNotLoad.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ModelCouldNotLoad`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsmodelcouldnotload-__construct }
public function __construct( string $modelName );
## Mvc\Model\Exceptions\ModelOrmServicesUnavailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ModelOrmServicesUnavailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ModelOrmServicesUnavailable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsmodelormservicesunavailable-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/PrimaryKeyAttributeNotSet.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsprimarykeyattributenotset-__construct }
public function __construct(
    string $attribute,
    string $className
);
## Mvc\Model\Exceptions\PrimaryKeyRequired Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/PrimaryKeyRequired.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\PrimaryKeyRequired`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsprimarykeyrequired-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\PropertyNotAccessible Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/PropertyNotAccessible.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\PropertyNotAccessible`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionspropertynotaccessible-__construct }
public function __construct(
    string $property,
    string $className
);
## Mvc\Model\Exceptions\RecordCannotRefresh Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/RecordCannotRefresh.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\RecordCannotRefresh`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsrecordcannotrefresh-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\RecordNotPersisted Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/RecordNotPersisted.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\RecordNotPersisted`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsrecordnotpersisted-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\ReferencedFieldsMismatch Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ReferencedFieldsMismatch.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ReferencedFieldsMismatch`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsreferencedfieldsmismatch-__construct }
public function __construct(
    string $relationType,
    string $entityName,
    string $referencedEntity
);
## Mvc\Model\Exceptions\RelationAliasMustBeString Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/RelationAliasMustBeString.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\RelationAliasMustBeString`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsrelationaliasmustbestring-__construct }
public function __construct(
    string $relationType,
    string $entityName,
    string $referencedEntity
);
## Mvc\Model\Exceptions\RelationNotDefined Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/RelationNotDefined.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\RelationNotDefined`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsrelationnotdefined-__construct }
public function __construct(
    string $className,
    string $alias
);
## Mvc\Model\Exceptions\RelationRequiresObjectOrArray Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/RelationRequiresObjectOrArray.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\RelationRequiresObjectOrArray`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsrelationrequiresobjectorarray-__construct }
public function __construct(
    string $className,
    string $relationName
);
## Mvc\Model\Exceptions\ResultsetColumnNotInMap Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/ResultsetColumnNotInMap.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\ResultsetColumnNotInMap`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsresultsetcolumnnotinmap-__construct }
public function __construct( string $key );
## Mvc\Model\Exceptions\RowIsImmutable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/RowIsImmutable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\RowIsImmutable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsrowisimmutable-__construct }
public function __construct();
## Mvc\Model\Exceptions\SnapshotsDisabled Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/SnapshotsDisabled.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\SnapshotsDisabled`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionssnapshotsdisabled-__construct }
public function __construct( string $className );
## Mvc\Model\Exceptions\StaticMethodRequiresOneArgument Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/StaticMethodRequiresOneArgument.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\StaticMethodRequiresOneArgument`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsstaticmethodrequiresoneargument-__construct }
public function __construct(
    string $method,
    string $className
);
## Mvc\Model\Exceptions\UnknownRelationType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/UnknownRelationType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\UnknownRelationType`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsunknownrelationtype-__construct }
public function __construct();
## Mvc\Model\Exceptions\UpdateSnapshotDisabled Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Exceptions/UpdateSnapshotDisabled.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Exceptions\UpdateSnapshotDisabled`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelexceptionsupdatesnapshotdisabled-__construct }
public function __construct( string $className );
## Mvc\Model\Manager Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Manager.zep){ .src-btn } Phalcon\Mvc\Model\Manager This components controls the initialization of models, keeping record of relations between the different models of the application. A ModelsManager is injected to a model via a Dependency Injector/Services Container such as Phalcon\Di\Di.
use Phalcon\Di\Di;
use Phalcon\Mvc\Model\Manager as ModelsManager;

$di = new Di();

$di->set(
    "modelsManager",
    function() {
        return new ModelsManager();
    }
);

$robot = new Robots($di);
- **`Phalcon\Mvc\Model\Manager`** — implements [`Phalcon\Mvc\Model\ManagerInterface`](#mvcmodelmanagerinterface), [`Phalcon\Di\InjectionAwareInterface`](phalcon_di.md#diinjectionawareinterface), [`Phalcon\Events\EventsAwareInterface`](phalcon_events.md#eventseventsawareinterface)
__Uses__ `Phalcon\Contracts\Mvc\Model\Relation\CacheKeyProvider` · `Phalcon\Db\Adapter\AdapterInterface` · `Phalcon\Di\DiInterface` · `Phalcon\Di\InjectionAwareInterface` · `Phalcon\Events\EventsAwareInterface` · `Phalcon\Events\ManagerInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Exceptions\InvalidConnectionService` · `Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable` · `Phalcon\Mvc\Model\Exceptions\ModelCouldNotLoad` · `Phalcon\Mvc\Model\Exceptions\ReferencedFieldsMismatch` · `Phalcon\Mvc\Model\Exceptions\RelationAliasMustBeString` · `Phalcon\Mvc\Model\Exceptions\UnknownRelationType` · `Phalcon\Mvc\Model\Query\Builder` · `Phalcon\Mvc\Model\Query\BuilderInterface` · `Phalcon\Mvc\Model\Query\StatusInterface` · `Phalcon\Support\Settings` · `ReflectionClass` · `ReflectionProperty` { .api-uses } ### Method Summary
public __destruct() Destroys the current PHQL cache public void addBehavior(ModelInterface $model,BehaviorInterface $behavior) Binds a behavior to a model public RelationInterface addBelongsTo(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation reverse many to one between two models public RelationInterface addHasMany(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation 1-n between two models public RelationInterface addHasManyToMany(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a relation n-m between two models public RelationInterface addHasOne(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models public RelationInterface addHasOneThrough(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a relation 1-1 between two models using an intermediate model public void clearReusableObjects() Clears the internal reusable list public BuilderInterface createBuilder( mixed $params = null ) Creates a Phalcon\Mvc\Model\Query\Builder public QueryInterface createQuery( string $phql ) Creates a Phalcon\Mvc\Model\Query without execute it public mixed executeQuery(string $phql,mixed $placeholders = null,mixed $types = null) Creates a Phalcon\Mvc\Model\Query and execute it public bool existsBelongsTo(string $modelName,string $modelRelation) Checks whether a model has a belongsTo relation with another model public bool existsHasMany(string $modelName,string $modelRelation) Checks whether a model has a hasMany relation with another model public bool existsHasManyToMany(string $modelName,string $modelRelation) Checks whether a model has a hasManyToMany relation with another model public bool existsHasOne(string $modelName,string $modelRelation) Checks whether a model has a hasOne relation with another model public bool existsHasOneThrough(string $modelName,string $modelRelation) Checks whether a model has a hasOneThrough relation with another model public RelationInterface[]|array getBelongsTo( ModelInterface $model ) Gets all the belongsTo relations defined in a model public ResultsetInterface|bool getBelongsToRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets belongsTo related records from a model public BuilderInterface|null getBuilder() Returns the newly created Phalcon\Mvc\Model\Query\Builder or null public string getConnectionService(ModelInterface $model,array $connectionServices) Returns the connection service name used to read or write data related to public EventsManagerInterface|null getCustomEventsManager( ModelInterface $model ) Returns a custom events manager related to a model or null if there is public DiInterface getDI() Returns the DependencyInjector container public EventsManagerInterface|null getEventsManager() Returns the internal event manager public RelationInterface[]|array getHasMany( ModelInterface $model ) Gets hasMany relations defined on a model public ResultsetInterface|bool getHasManyRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets hasMany related records from a model public RelationInterface[]|array getHasManyToMany( ModelInterface $model ) Gets hasManyToMany relations defined on a model public array getHasOne( ModelInterface $model ) Gets hasOne relations defined on a model public RelationInterface[] getHasOneAndHasMany( ModelInterface $model ) Gets hasOne relations defined on a model public ModelInterface|bool getHasOneRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets belongsTo related records from a model public RelationInterface[]|array getHasOneThrough( ModelInterface $model ) Gets hasOneThrough relations defined on a model public ModelInterface|null getLastInitialized() Get last initialized model public QueryInterface getLastQuery() Returns the last query created or executed in the models manager public string getModelPrefix() Returns the prefix for all model sources. public string|null getModelSchema( ModelInterface $model ) Returns the mapped schema for a model public string getModelSource( ModelInterface $model ) Returns the mapped source for a model public AdapterInterface getReadConnection( ModelInterface $model ) Returns the connection to read data related to a model public string getReadConnectionService( ModelInterface $model ) Returns the connection service name used to read data related to a model public RelationInterface|bool getRelationByAlias(string $modelName,string $alias) Returns a relation by its alias public getRelationRecords(RelationInterface $relation,ModelInterface $record,mixed $parameters = null,string $method = null) Helper method to query records based on a relation definition public RelationInterface[] getRelations( string $modelName ) Query all the relationships defined on a model public RelationInterface[]|bool getRelationsBetween(string $first,string $second) Query the first relationship defined between two models public getReusableRecords(string $modelName,string $key) Returns a reusable object from the internal list public AdapterInterface getWriteConnection( ModelInterface $model ) Returns the connection to write data related to a model public string getWriteConnectionService( ModelInterface $model ) Returns the connection service name used to write data related to a model public bool hasBelongsTo(string $modelName,string $modelRelation) Checks whether a model has a belongsTo relation with another model public bool hasHasMany(string $modelName,string $modelRelation) Checks whether a model has a hasMany relation with another model public bool hasHasManyToMany(string $modelName,string $modelRelation) Checks whether a model has a hasManyToMany relation with another model public bool hasHasOne(string $modelName,string $modelRelation) Checks whether a model has a hasOne relation with another model public bool hasHasOneThrough(string $modelName,string $modelRelation) Checks whether a model has a hasOneThrough relation with another model public bool initialize( ModelInterface $model ) Initializes a model in the model manager public bool isInitialized( string $className ) Check whether a model is already initialized public bool isKeepingSnapshots( ModelInterface $model ) Checks if a model is keeping snapshots for the queried records public bool isUsingDynamicUpdate( ModelInterface $model ) Checks if a model is using dynamic update instead of all-field update public bool isVisibleModelProperty(ModelInterface $model,string $property) Check whether a model property is declared as public. public void keepSnapshots(ModelInterface $model,bool $keepSnapshots) Sets if a model must keep snapshots public ModelInterface load( string $modelName ) Loads a model throwing an exception if it does not exist public missingMethod(ModelInterface $model,string $eventName,mixed $data) Dispatch an event to the listeners and behaviors public notifyEvent(string $eventName,ModelInterface $model) Receives events generated in the models and dispatches them to an public void removeBehavior(ModelInterface $model,string $behaviorClass) Removes a behavior from a model public void setConnectionService(ModelInterface $model,string $connectionService) Sets both write and read connection service for a model public void setCustomEventsManager(ModelInterface $model,EventsManagerInterface $eventsManager) Sets a custom events manager for a specific model public void setDI( DiInterface $container ) Sets the DependencyInjector container public void setEventsManager( EventsManagerInterface $eventsManager ) Sets a global events manager public void setModelPrefix( string $prefix ) Sets the prefix for all model sources. public void setModelSchema(ModelInterface $model,string $schema) Sets the mapped schema for a model public void setModelSource(ModelInterface $model,string $source) Sets the mapped source for a model public void setReadConnectionService(ModelInterface $model,string $connectionService) Sets read connection service for a model public void setReusableRecords(string $modelName,string $key,mixed $records) Stores a reusable record in the internal list public void setWriteConnectionService(ModelInterface $model,string $connectionService) Sets write connection service for a model public void useDynamicUpdate(ModelInterface $model,bool $dynamicUpdate) Sets if a model must use dynamic update instead of the all-field update protected AdapterInterface getConnection(ModelInterface $model,array $connectionServices) Returns the connection to read or write data related to a model protected array mergeFindParameters(mixed $findParamsOne,mixed $findParamsTwo) Merge two arrays of find parameters
### Properties
protected array $aliases = []
protected array $behaviors = [] Models' behaviors
protected array $belongsTo = [] Belongs to relations
protected array $belongsToSingle = [] All the relationships by model
protected BuilderInterface|null $builder = null
protected DiInterface|null $container = null
protected array $customEventsManager = []
protected array $dynamicUpdate = [] Does the model use dynamic update, instead of updating all rows?
protected EventsManagerInterface|null $eventsManager = null
protected array $hasMany = [] Has many relations
protected array $hasManySingle = [] Has many relations by model
protected array $hasManyToMany = [] Has many-Through relations
protected array $hasManyToManySingle = [] Has many-Through relations by model
protected array $hasOne = [] Has one relations
protected array $hasOneSingle = [] Has one relations by model
protected array $hasOneThrough = [] Has one through relations
protected array $hasOneThroughSingle = [] Has one through relations by model
protected array $initialized = [] Mark initialized models
protected array $keepSnapshots = []
protected ModelInterface|null $lastInitialized = null Last model initialized
protected QueryInterface|null $lastQuery = null Last query created/executed
protected array $modelVisibility = []
protected string $prefix = ""
protected array $readConnectionServices = []
protected array $reusable = [] Stores a list of reusable instances
protected array $schemas = []
protected array $sources = []
protected array $writeConnectionServices = []
### Methods
Public · 70
#### `__destruct()` { #mvcmodelmanager-__destruct }
public function __destruct();
Destroys the current PHQL cache #### `addBehavior()` { #mvcmodelmanager-addbehavior }
public function addBehavior(
    ModelInterface $model,
    BehaviorInterface $behavior
): void;
Binds a behavior to a model #### `addBelongsTo()` { #mvcmodelmanager-addbelongsto }
public function addBelongsTo(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setup a relation reverse many to one between two models #### `addHasMany()` { #mvcmodelmanager-addhasmany }
public function addHasMany(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setup a relation 1-n between two models #### `addHasManyToMany()` { #mvcmodelmanager-addhasmanytomany }
public function addHasManyToMany(
    ModelInterface $model,
    mixed $fields,
    string $intermediateModel,
    mixed $intermediateFields,
    mixed $intermediateReferencedFields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setups a relation n-m between two models #### `addHasOne()` { #mvcmodelmanager-addhasone }
public function addHasOne(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setup a 1-1 relation between two models #### `addHasOneThrough()` { #mvcmodelmanager-addhasonethrough }
public function addHasOneThrough(
    ModelInterface $model,
    mixed $fields,
    string $intermediateModel,
    mixed $intermediateFields,
    mixed $intermediateReferencedFields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setups a relation 1-1 between two models using an intermediate model #### `clearReusableObjects()` { #mvcmodelmanager-clearreusableobjects }
public function clearReusableObjects(): void;
Clears the internal reusable list #### `createBuilder()` { #mvcmodelmanager-createbuilder }
public function createBuilder( mixed $params = null ): BuilderInterface;
Creates a Phalcon\Mvc\Model\Query\Builder #### `createQuery()` { #mvcmodelmanager-createquery }
public function createQuery( string $phql ): QueryInterface;
Creates a Phalcon\Mvc\Model\Query without execute it #### `executeQuery()` { #mvcmodelmanager-executequery }
public function executeQuery(
    string $phql,
    mixed $placeholders = null,
    mixed $types = null
): mixed;
Creates a Phalcon\Mvc\Model\Query and execute it
$model = new Robots();
$manager = $model->getModelsManager();

// \Phalcon\Mvc\Model\Resultset\Simple
$manager->executeQuery('SELECT * FROM Robots');

// \Phalcon\Mvc\Model\Resultset\Complex
$manager->executeQuery('SELECT COUNT(type) FROM Robots GROUP BY type');

// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('INSERT INTO Robots (id) VALUES (1)');

// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('UPDATE Robots SET id = 0 WHERE id = :id:', ['id' => 1]);

// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('DELETE FROM Robots WHERE id = :id:', ['id' => 1]);
#### `existsBelongsTo()` { #mvcmodelmanager-existsbelongsto }
public function existsBelongsTo(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a belongsTo relation with another model #### `existsHasMany()` { #mvcmodelmanager-existshasmany }
public function existsHasMany(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasMany relation with another model #### `existsHasManyToMany()` { #mvcmodelmanager-existshasmanytomany }
public function existsHasManyToMany(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasManyToMany relation with another model #### `existsHasOne()` { #mvcmodelmanager-existshasone }
public function existsHasOne(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasOne relation with another model #### `existsHasOneThrough()` { #mvcmodelmanager-existshasonethrough }
public function existsHasOneThrough(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasOneThrough relation with another model #### `getBelongsTo()` { #mvcmodelmanager-getbelongsto }
public function getBelongsTo( ModelInterface $model ): RelationInterface[]|array;
Gets all the belongsTo relations defined in a model
$relations = $modelsManager->getBelongsTo(
    new Robots()
);
#### `getBelongsToRecords()` { #mvcmodelmanager-getbelongstorecords }
public function getBelongsToRecords(
    string $modelName,
    string $modelRelation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
): ResultsetInterface|bool;
Gets belongsTo related records from a model #### `getBuilder()` { #mvcmodelmanager-getbuilder }
public function getBuilder(): BuilderInterface|null;
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null #### `getConnectionService()` { #mvcmodelmanager-getconnectionservice }
public function getConnectionService(
    ModelInterface $model,
    array $connectionServices
): string;
Returns the connection service name used to read or write data related to a model depending on the connection services #### `getCustomEventsManager()` { #mvcmodelmanager-getcustomeventsmanager }
public function getCustomEventsManager( ModelInterface $model ): EventsManagerInterface|null;
Returns a custom events manager related to a model or null if there is no related events manager #### `getDI()` { #mvcmodelmanager-getdi }
public function getDI(): DiInterface;
Returns the DependencyInjector container #### `getEventsManager()` { #mvcmodelmanager-geteventsmanager }
public function getEventsManager(): EventsManagerInterface|null;
Returns the internal event manager #### `getHasMany()` { #mvcmodelmanager-gethasmany }
public function getHasMany( ModelInterface $model ): RelationInterface[]|array;
Gets hasMany relations defined on a model #### `getHasManyRecords()` { #mvcmodelmanager-gethasmanyrecords }
public function getHasManyRecords(
    string $modelName,
    string $modelRelation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
): ResultsetInterface|bool;
Gets hasMany related records from a model #### `getHasManyToMany()` { #mvcmodelmanager-gethasmanytomany }
public function getHasManyToMany( ModelInterface $model ): RelationInterface[]|array;
Gets hasManyToMany relations defined on a model #### `getHasOne()` { #mvcmodelmanager-gethasone }
public function getHasOne( ModelInterface $model ): array;
Gets hasOne relations defined on a model #### `getHasOneAndHasMany()` { #mvcmodelmanager-gethasoneandhasmany }
public function getHasOneAndHasMany( ModelInterface $model ): RelationInterface[];
Gets hasOne relations defined on a model #### `getHasOneRecords()` { #mvcmodelmanager-gethasonerecords }
public function getHasOneRecords(
    string $modelName,
    string $modelRelation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
): ModelInterface|bool;
Gets belongsTo related records from a model #### `getHasOneThrough()` { #mvcmodelmanager-gethasonethrough }
public function getHasOneThrough( ModelInterface $model ): RelationInterface[]|array;
Gets hasOneThrough relations defined on a model #### `getLastInitialized()` { #mvcmodelmanager-getlastinitialized }
public function getLastInitialized(): ModelInterface|null;
Get last initialized model #### `getLastQuery()` { #mvcmodelmanager-getlastquery }
public function getLastQuery(): QueryInterface;
Returns the last query created or executed in the models manager #### `getModelPrefix()` { #mvcmodelmanager-getmodelprefix }
public function getModelPrefix(): string;
Returns the prefix for all model sources. #### `getModelSchema()` { #mvcmodelmanager-getmodelschema }
public function getModelSchema( ModelInterface $model ): string|null;
Returns the mapped schema for a model #### `getModelSource()` { #mvcmodelmanager-getmodelsource }
public function getModelSource( ModelInterface $model ): string;
Returns the mapped source for a model #### `getReadConnection()` { #mvcmodelmanager-getreadconnection }
public function getReadConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to read data related to a model #### `getReadConnectionService()` { #mvcmodelmanager-getreadconnectionservice }
public function getReadConnectionService( ModelInterface $model ): string;
Returns the connection service name used to read data related to a model #### `getRelationByAlias()` { #mvcmodelmanager-getrelationbyalias }
public function getRelationByAlias(
    string $modelName,
    string $alias
): RelationInterface|bool;
Returns a relation by its alias #### `getRelationRecords()` { #mvcmodelmanager-getrelationrecords }
public function getRelationRecords(
    RelationInterface $relation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
);
Helper method to query records based on a relation definition #### `getRelations()` { #mvcmodelmanager-getrelations }
public function getRelations( string $modelName ): RelationInterface[];
Query all the relationships defined on a model #### `getRelationsBetween()` { #mvcmodelmanager-getrelationsbetween }
public function getRelationsBetween(
    string $first,
    string $second
): RelationInterface[]|bool;
Query the first relationship defined between two models #### `getReusableRecords()` { #mvcmodelmanager-getreusablerecords }
public function getReusableRecords(
    string $modelName,
    string $key
);
Returns a reusable object from the internal list #### `getWriteConnection()` { #mvcmodelmanager-getwriteconnection }
public function getWriteConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to write data related to a model #### `getWriteConnectionService()` { #mvcmodelmanager-getwriteconnectionservice }
public function getWriteConnectionService( ModelInterface $model ): string;
Returns the connection service name used to write data related to a model #### `hasBelongsTo()` { #mvcmodelmanager-hasbelongsto }
public function hasBelongsTo(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a belongsTo relation with another model #### `hasHasMany()` { #mvcmodelmanager-hashasmany }
public function hasHasMany(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasMany relation with another model #### `hasHasManyToMany()` { #mvcmodelmanager-hashasmanytomany }
public function hasHasManyToMany(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasManyToMany relation with another model #### `hasHasOne()` { #mvcmodelmanager-hashasone }
public function hasHasOne(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasOne relation with another model #### `hasHasOneThrough()` { #mvcmodelmanager-hashasonethrough }
public function hasHasOneThrough(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasOneThrough relation with another model #### `initialize()` { #mvcmodelmanager-initialize }
public function initialize( ModelInterface $model ): bool;
Initializes a model in the model manager #### `isInitialized()` { #mvcmodelmanager-isinitialized }
public function isInitialized( string $className ): bool;
Check whether a model is already initialized #### `isKeepingSnapshots()` { #mvcmodelmanager-iskeepingsnapshots }
public function isKeepingSnapshots( ModelInterface $model ): bool;
Checks if a model is keeping snapshots for the queried records #### `isUsingDynamicUpdate()` { #mvcmodelmanager-isusingdynamicupdate }
public function isUsingDynamicUpdate( ModelInterface $model ): bool;
Checks if a model is using dynamic update instead of all-field update #### `isVisibleModelProperty()` { #mvcmodelmanager-isvisiblemodelproperty }
final public function isVisibleModelProperty(
    ModelInterface $model,
    string $property
): bool;
Check whether a model property is declared as public.
$isPublic = $manager->isVisibleModelProperty(
    new Robots(),
    "name"
);
#### `keepSnapshots()` { #mvcmodelmanager-keepsnapshots }
public function keepSnapshots(
    ModelInterface $model,
    bool $keepSnapshots
): void;
Sets if a model must keep snapshots #### `load()` { #mvcmodelmanager-load }
public function load( string $modelName ): ModelInterface;
Loads a model throwing an exception if it does not exist #### `missingMethod()` { #mvcmodelmanager-missingmethod }
public function missingMethod(
    ModelInterface $model,
    string $eventName,
    mixed $data
);
Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented #### `notifyEvent()` { #mvcmodelmanager-notifyevent }
public function notifyEvent(
    string $eventName,
    ModelInterface $model
);
Receives events generated in the models and dispatches them to an events-manager if available. Notify the behaviors that are listening in the model #### `removeBehavior()` { #mvcmodelmanager-removebehavior }
public function removeBehavior(
    ModelInterface $model,
    string $behaviorClass
): void;
Removes a behavior from a model #### `setConnectionService()` { #mvcmodelmanager-setconnectionservice }
public function setConnectionService(
    ModelInterface $model,
    string $connectionService
): void;
Sets both write and read connection service for a model #### `setCustomEventsManager()` { #mvcmodelmanager-setcustomeventsmanager }
public function setCustomEventsManager(
    ModelInterface $model,
    EventsManagerInterface $eventsManager
): void;
Sets a custom events manager for a specific model #### `setDI()` { #mvcmodelmanager-setdi }
public function setDI( DiInterface $container ): void;
Sets the DependencyInjector container #### `setEventsManager()` { #mvcmodelmanager-seteventsmanager }
public function setEventsManager( EventsManagerInterface $eventsManager ): void;
Sets a global events manager #### `setModelPrefix()` { #mvcmodelmanager-setmodelprefix }
public function setModelPrefix( string $prefix ): void;
Sets the prefix for all model sources.
use Phalcon\Mvc\Model\Manager;

$di->set(
    "modelsManager",
    function () {
        $modelsManager = new Manager();

        $modelsManager->setModelPrefix("wp_");

        return $modelsManager;
    }
);

$robots = new Robots();

echo $robots->getSource(); // wp_robots
$param string $prefix #### `setModelSchema()` { #mvcmodelmanager-setmodelschema }
public function setModelSchema(
    ModelInterface $model,
    string $schema
): void;
Sets the mapped schema for a model #### `setModelSource()` { #mvcmodelmanager-setmodelsource }
public function setModelSource(
    ModelInterface $model,
    string $source
): void;
Sets the mapped source for a model #### `setReadConnectionService()` { #mvcmodelmanager-setreadconnectionservice }
public function setReadConnectionService(
    ModelInterface $model,
    string $connectionService
): void;
Sets read connection service for a model #### `setReusableRecords()` { #mvcmodelmanager-setreusablerecords }
public function setReusableRecords(
    string $modelName,
    string $key,
    mixed $records
): void;
Stores a reusable record in the internal list #### `setWriteConnectionService()` { #mvcmodelmanager-setwriteconnectionservice }
public function setWriteConnectionService(
    ModelInterface $model,
    string $connectionService
): void;
Sets write connection service for a model #### `useDynamicUpdate()` { #mvcmodelmanager-usedynamicupdate }
public function useDynamicUpdate(
    ModelInterface $model,
    bool $dynamicUpdate
): void;
Sets if a model must use dynamic update instead of the all-field update
Protected · 2
#### `getConnection()` { #mvcmodelmanager-getconnection }
protected function getConnection(
    ModelInterface $model,
    array $connectionServices
): AdapterInterface;
Returns the connection to read or write data related to a model depending on the connection services. #### `mergeFindParameters()` { #mvcmodelmanager-mergefindparameters }
final protected function mergeFindParameters(
    mixed $findParamsOne,
    mixed $findParamsTwo
): array;
Merge two arrays of find parameters ## Mvc\Model\ManagerInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/ManagerInterface.zep){ .src-btn } Phalcon\Mvc\Model\ManagerInterface Interface for Phalcon\Mvc\Model\Manager
- **`Phalcon\Mvc\Model\ManagerInterface`**
__Uses__ `Phalcon\Db\Adapter\AdapterInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Query\BuilderInterface` · `Phalcon\Mvc\Model\Query\StatusInterface` { .api-uses } ### Method Summary
public void addBehavior(ModelInterface $model,BehaviorInterface $behavior) Binds a behavior to a model public RelationInterface addBelongsTo(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation reverse 1-1 between two models public RelationInterface addHasMany(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation 1-n between two models public RelationInterface addHasManyToMany(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a relation n-m between two models public RelationInterface addHasOne(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models public RelationInterface addHasOneThrough(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a 1-1 relation between two models using an intermediate table public void clearReusableObjects() Clears the internal reusable list public BuilderInterface createBuilder( mixed $params = null ) Creates a Phalcon\Mvc\Model\Query\Builder public QueryInterface createQuery( string $phql ) Creates a Phalcon\Mvc\Model\Query without execute it public mixed executeQuery(string $phql,mixed $placeholders = null,mixed $types = null) Creates a Phalcon\Mvc\Model\Query and execute it public RelationInterface[]|array getBelongsTo( ModelInterface $model ) Gets belongsTo relations defined on a model public ResultsetInterface|bool getBelongsToRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets belongsTo related records from a model public BuilderInterface|null getBuilder() Returns the newly created Phalcon\Mvc\Model\Query\Builder or null public RelationInterface[]|array getHasMany( ModelInterface $model ) Gets hasMany relations defined on a model public ResultsetInterface|bool getHasManyRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets hasMany related records from a model public RelationInterface[]|array getHasManyToMany( ModelInterface $model ) Gets hasManyToMany relations defined on a model public RelationInterface[]|array getHasOne( ModelInterface $model ) Gets hasOne relations defined on a model public RelationInterface[] getHasOneAndHasMany( ModelInterface $model ) Gets hasOne relations defined on a model public ModelInterface|bool getHasOneRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets hasOne related records from a model public RelationInterface[]|array getHasOneThrough( ModelInterface $model ) Gets hasOneThrough relations defined on a model public ModelInterface|null getLastInitialized() Get last initialized model public QueryInterface getLastQuery() Returns the last query created or executed in the models manager public string|null getModelSchema( ModelInterface $model ) Returns the mapped schema for a model public string getModelSource( ModelInterface $model ) Returns the mapped source for a model public AdapterInterface getReadConnection( ModelInterface $model ) Returns the connection to read data related to a model public string getReadConnectionService( ModelInterface $model ) Returns the connection service name used to read data related to a model public RelationInterface|bool getRelationByAlias(string $modelName,string $alias) Returns a relation by its alias public getRelationRecords(RelationInterface $relation,ModelInterface $record,mixed $parameters = null,string $method = null) Helper method to query records based on a relation definition public RelationInterface[] getRelations( string $modelName ) Query all the relationships defined on a model public RelationInterface[]|bool getRelationsBetween(string $first,string $second) Query the relations between two models public getReusableRecords(string $modelName,string $key) Returns a reusable object from the internal list public AdapterInterface getWriteConnection( ModelInterface $model ) Returns the connection to write data related to a model public string getWriteConnectionService( ModelInterface $model ) Returns the connection service name used to write data related to a model public bool hasBelongsTo(string $modelName,string $modelRelation) Checks whether a model has a belongsTo relation with another model public bool hasHasMany(string $modelName,string $modelRelation) Checks whether a model has a hasMany relation with another model public bool hasHasManyToMany(string $modelName,string $modelRelation) Checks whether a model has a hasManyToMany relation with another model public bool hasHasOne(string $modelName,string $modelRelation) Checks whether a model has a hasOne relation with another model public bool hasHasOneThrough(string $modelName,string $modelRelation) Checks whether a model has a hasOneThrough relation with another model public initialize( ModelInterface $model ) Initializes a model in the model manager public bool isInitialized( string $className ) Check of a model is already initialized public bool isKeepingSnapshots( ModelInterface $model ) Checks if a model is keeping snapshots for the queried records public bool isUsingDynamicUpdate( ModelInterface $model ) Checks if a model is using dynamic update instead of all-field update public bool isVisibleModelProperty(ModelInterface $model,string $property) Check whether a model property is declared as public. public void keepSnapshots(ModelInterface $model,bool $keepSnapshots) Sets if a model must keep snapshots public ModelInterface load( string $modelName ) Loads a model throwing an exception if it does not exist public missingMethod(ModelInterface $model,string $eventName,mixed $data) Dispatch an event to the listeners and behaviors public notifyEvent(string $eventName,ModelInterface $model) Receives events generated in the models and dispatches them to an events-manager if available public void removeBehavior(ModelInterface $model,string $behaviorClass) Removes a behavior from a model public void setConnectionService(ModelInterface $model,string $connectionService) Sets both write and read connection service for a model public void setModelSchema(ModelInterface $model,string $schema) Sets the mapped schema for a model public void setModelSource(ModelInterface $model,string $source) Sets the mapped source for a model public void setReadConnectionService(ModelInterface $model,string $connectionService) Sets read connection service for a model public void setReusableRecords(string $modelName,string $key,mixed $records) Stores a reusable record in the internal list public setWriteConnectionService(ModelInterface $model,string $connectionService) Sets write connection service for a model public void useDynamicUpdate(ModelInterface $model,bool $dynamicUpdate) Sets if a model must use dynamic update instead of the all-field update
### Methods
Public · 55
#### `addBehavior()` { #mvcmodelmanagerinterface-addbehavior }
public function addBehavior(
    ModelInterface $model,
    BehaviorInterface $behavior
): void;
Binds a behavior to a model #### `addBelongsTo()` { #mvcmodelmanagerinterface-addbelongsto }
public function addBelongsTo(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setup a relation reverse 1-1 between two models #### `addHasMany()` { #mvcmodelmanagerinterface-addhasmany }
public function addHasMany(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setup a relation 1-n between two models #### `addHasManyToMany()` { #mvcmodelmanagerinterface-addhasmanytomany }
public function addHasManyToMany(
    ModelInterface $model,
    mixed $fields,
    string $intermediateModel,
    mixed $intermediateFields,
    mixed $intermediateReferencedFields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setups a relation n-m between two models #### `addHasOne()` { #mvcmodelmanagerinterface-addhasone }
public function addHasOne(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setup a 1-1 relation between two models #### `addHasOneThrough()` { #mvcmodelmanagerinterface-addhasonethrough }
public function addHasOneThrough(
    ModelInterface $model,
    mixed $fields,
    string $intermediateModel,
    mixed $intermediateFields,
    mixed $intermediateReferencedFields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;
Setups a 1-1 relation between two models using an intermediate table #### `clearReusableObjects()` { #mvcmodelmanagerinterface-clearreusableobjects }
public function clearReusableObjects(): void;
Clears the internal reusable list #### `createBuilder()` { #mvcmodelmanagerinterface-createbuilder }
public function createBuilder( mixed $params = null ): BuilderInterface;
Creates a Phalcon\Mvc\Model\Query\Builder #### `createQuery()` { #mvcmodelmanagerinterface-createquery }
public function createQuery( string $phql ): QueryInterface;
Creates a Phalcon\Mvc\Model\Query without execute it #### `executeQuery()` { #mvcmodelmanagerinterface-executequery }
public function executeQuery(
    string $phql,
    mixed $placeholders = null,
    mixed $types = null
): mixed;
Creates a Phalcon\Mvc\Model\Query and execute it #### `getBelongsTo()` { #mvcmodelmanagerinterface-getbelongsto }
public function getBelongsTo( ModelInterface $model ): RelationInterface[]|array;
Gets belongsTo relations defined on a model #### `getBelongsToRecords()` { #mvcmodelmanagerinterface-getbelongstorecords }
public function getBelongsToRecords(
    string $modelName,
    string $modelRelation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
): ResultsetInterface|bool;
Gets belongsTo related records from a model #### `getBuilder()` { #mvcmodelmanagerinterface-getbuilder }
public function getBuilder(): BuilderInterface|null;
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null #### `getHasMany()` { #mvcmodelmanagerinterface-gethasmany }
public function getHasMany( ModelInterface $model ): RelationInterface[]|array;
Gets hasMany relations defined on a model #### `getHasManyRecords()` { #mvcmodelmanagerinterface-gethasmanyrecords }
public function getHasManyRecords(
    string $modelName,
    string $modelRelation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
): ResultsetInterface|bool;
Gets hasMany related records from a model #### `getHasManyToMany()` { #mvcmodelmanagerinterface-gethasmanytomany }
public function getHasManyToMany( ModelInterface $model ): RelationInterface[]|array;
Gets hasManyToMany relations defined on a model #### `getHasOne()` { #mvcmodelmanagerinterface-gethasone }
public function getHasOne( ModelInterface $model ): RelationInterface[]|array;
Gets hasOne relations defined on a model #### `getHasOneAndHasMany()` { #mvcmodelmanagerinterface-gethasoneandhasmany }
public function getHasOneAndHasMany( ModelInterface $model ): RelationInterface[];
Gets hasOne relations defined on a model #### `getHasOneRecords()` { #mvcmodelmanagerinterface-gethasonerecords }
public function getHasOneRecords(
    string $modelName,
    string $modelRelation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
): ModelInterface|bool;
Gets hasOne related records from a model #### `getHasOneThrough()` { #mvcmodelmanagerinterface-gethasonethrough }
public function getHasOneThrough( ModelInterface $model ): RelationInterface[]|array;
Gets hasOneThrough relations defined on a model #### `getLastInitialized()` { #mvcmodelmanagerinterface-getlastinitialized }
public function getLastInitialized(): ModelInterface|null;
Get last initialized model #### `getLastQuery()` { #mvcmodelmanagerinterface-getlastquery }
public function getLastQuery(): QueryInterface;
Returns the last query created or executed in the models manager #### `getModelSchema()` { #mvcmodelmanagerinterface-getmodelschema }
public function getModelSchema( ModelInterface $model ): string|null;
Returns the mapped schema for a model #### `getModelSource()` { #mvcmodelmanagerinterface-getmodelsource }
public function getModelSource( ModelInterface $model ): string;
Returns the mapped source for a model #### `getReadConnection()` { #mvcmodelmanagerinterface-getreadconnection }
public function getReadConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to read data related to a model #### `getReadConnectionService()` { #mvcmodelmanagerinterface-getreadconnectionservice }
public function getReadConnectionService( ModelInterface $model ): string;
Returns the connection service name used to read data related to a model #### `getRelationByAlias()` { #mvcmodelmanagerinterface-getrelationbyalias }
public function getRelationByAlias(
    string $modelName,
    string $alias
): RelationInterface|bool;
Returns a relation by its alias #### `getRelationRecords()` { #mvcmodelmanagerinterface-getrelationrecords }
public function getRelationRecords(
    RelationInterface $relation,
    ModelInterface $record,
    mixed $parameters = null,
    string $method = null
);
Helper method to query records based on a relation definition #### `getRelations()` { #mvcmodelmanagerinterface-getrelations }
public function getRelations( string $modelName ): RelationInterface[];
Query all the relationships defined on a model #### `getRelationsBetween()` { #mvcmodelmanagerinterface-getrelationsbetween }
public function getRelationsBetween(
    string $first,
    string $second
): RelationInterface[]|bool;
Query the relations between two models #### `getReusableRecords()` { #mvcmodelmanagerinterface-getreusablerecords }
public function getReusableRecords(
    string $modelName,
    string $key
);
Returns a reusable object from the internal list #### `getWriteConnection()` { #mvcmodelmanagerinterface-getwriteconnection }
public function getWriteConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to write data related to a model #### `getWriteConnectionService()` { #mvcmodelmanagerinterface-getwriteconnectionservice }
public function getWriteConnectionService( ModelInterface $model ): string;
Returns the connection service name used to write data related to a model #### `hasBelongsTo()` { #mvcmodelmanagerinterface-hasbelongsto }
public function hasBelongsTo(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a belongsTo relation with another model #### `hasHasMany()` { #mvcmodelmanagerinterface-hashasmany }
public function hasHasMany(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasMany relation with another model #### `hasHasManyToMany()` { #mvcmodelmanagerinterface-hashasmanytomany }
public function hasHasManyToMany(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasManyToMany relation with another model #### `hasHasOne()` { #mvcmodelmanagerinterface-hashasone }
public function hasHasOne(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasOne relation with another model #### `hasHasOneThrough()` { #mvcmodelmanagerinterface-hashasonethrough }
public function hasHasOneThrough(
    string $modelName,
    string $modelRelation
): bool;
Checks whether a model has a hasOneThrough relation with another model #### `initialize()` { #mvcmodelmanagerinterface-initialize }
public function initialize( ModelInterface $model );
Initializes a model in the model manager #### `isInitialized()` { #mvcmodelmanagerinterface-isinitialized }
public function isInitialized( string $className ): bool;
Check of a model is already initialized #### `isKeepingSnapshots()` { #mvcmodelmanagerinterface-iskeepingsnapshots }
public function isKeepingSnapshots( ModelInterface $model ): bool;
Checks if a model is keeping snapshots for the queried records #### `isUsingDynamicUpdate()` { #mvcmodelmanagerinterface-isusingdynamicupdate }
public function isUsingDynamicUpdate( ModelInterface $model ): bool;
Checks if a model is using dynamic update instead of all-field update #### `isVisibleModelProperty()` { #mvcmodelmanagerinterface-isvisiblemodelproperty }
public function isVisibleModelProperty(
    ModelInterface $model,
    string $property
): bool;
Check whether a model property is declared as public.
$isPublic = $manager->isVisibleModelProperty(
    new Robots(),
    "name"
);
#### `keepSnapshots()` { #mvcmodelmanagerinterface-keepsnapshots }
public function keepSnapshots(
    ModelInterface $model,
    bool $keepSnapshots
): void;
Sets if a model must keep snapshots #### `load()` { #mvcmodelmanagerinterface-load }
public function load( string $modelName ): ModelInterface;
Loads a model throwing an exception if it does not exist #### `missingMethod()` { #mvcmodelmanagerinterface-missingmethod }
public function missingMethod(
    ModelInterface $model,
    string $eventName,
    mixed $data
);
Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one is implemented #### `notifyEvent()` { #mvcmodelmanagerinterface-notifyevent }
public function notifyEvent(
    string $eventName,
    ModelInterface $model
);
Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model #### `removeBehavior()` { #mvcmodelmanagerinterface-removebehavior }
public function removeBehavior(
    ModelInterface $model,
    string $behaviorClass
): void;
Removes a behavior from a model #### `setConnectionService()` { #mvcmodelmanagerinterface-setconnectionservice }
public function setConnectionService(
    ModelInterface $model,
    string $connectionService
): void;
Sets both write and read connection service for a model #### `setModelSchema()` { #mvcmodelmanagerinterface-setmodelschema }
public function setModelSchema(
    ModelInterface $model,
    string $schema
): void;
Sets the mapped schema for a model #### `setModelSource()` { #mvcmodelmanagerinterface-setmodelsource }
public function setModelSource(
    ModelInterface $model,
    string $source
): void;
Sets the mapped source for a model #### `setReadConnectionService()` { #mvcmodelmanagerinterface-setreadconnectionservice }
public function setReadConnectionService(
    ModelInterface $model,
    string $connectionService
): void;
Sets read connection service for a model #### `setReusableRecords()` { #mvcmodelmanagerinterface-setreusablerecords }
public function setReusableRecords(
    string $modelName,
    string $key,
    mixed $records
): void;
Stores a reusable record in the internal list #### `setWriteConnectionService()` { #mvcmodelmanagerinterface-setwriteconnectionservice }
public function setWriteConnectionService(
    ModelInterface $model,
    string $connectionService
);
Sets write connection service for a model #### `useDynamicUpdate()` { #mvcmodelmanagerinterface-usedynamicupdate }
public function useDynamicUpdate(
    ModelInterface $model,
    bool $dynamicUpdate
): void;
Sets if a model must use dynamic update instead of the all-field update ## Mvc\Model\MetaData Abstract [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData.zep){ .src-btn } Phalcon\Mvc\Model\MetaData Because Phalcon\Mvc\Model requires meta-data like field names, data types, primary keys, etc. This component collect them and store for further querying by Phalcon\Mvc\Model. Phalcon\Mvc\Model\MetaData can also use adapters to store temporarily or permanently the meta-data. A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes:
$metaData = new \Phalcon\Mvc\Model\MetaData\Memory();

$attributes = $metaData->getAttributes(
    new Robots()
);

print_r($attributes);
Each model's metadata is stored as two positional arrays addressed by two constant families. Both families count from 0 and therefore share numeric values, so a metadata array is only meaningful together with the family that indexes it. The metadata cache adapters persist these arrays verbatim, so the slot layout is a stored format: reordering a slot invalidates existing caches. Attribute metadata array (`MODELS_*` family): | Slot | Constant | Contents | |------|-----------------------------------|-------------------------------------------------| | 0 | `MODELS_ATTRIBUTES` | All mapped attribute (column) names | | 1 | `MODELS_PRIMARY_KEY` | Primary-key attributes | | 2 | `MODELS_NON_PRIMARY_KEY` | Non-primary-key attributes | | 3 | `MODELS_NOT_NULL` | Attributes declared `NOT NULL` | | 4 | `MODELS_DATA_TYPES` | attribute => column data type | | 5 | `MODELS_DATA_TYPES_NUMERIC` | Attributes with a numeric type | | 6 | `MODELS_DATE_AT` | Reserved (declared, currently unused) | | 7 | `MODELS_DATE_IN` | Reserved (declared, currently unused) | | 8 | `MODELS_IDENTITY_COLUMN` | The auto-increment identity attribute | | 9 | `MODELS_DATA_TYPES_BIND` | attribute => PDO bind type | | 10 | `MODELS_AUTOMATIC_DEFAULT_INSERT` | Attributes omitted from `INSERT` (DB-defaulted) | | 11 | `MODELS_AUTOMATIC_DEFAULT_UPDATE` | Attributes omitted from `UPDATE` (DB-defaulted) | | 12 | `MODELS_DEFAULT_VALUES` | attribute => default value | | 13 | `MODELS_EMPTY_STRING_VALUES` | Attributes that keep `''` instead of `NULL` | Column-map array (`MODELS_COLUMN_MAP` family), present only when a column map is defined: | Slot | Constant | Contents | |------|-----------------------------|---------------------| | 0 | `MODELS_COLUMN_MAP` | column => attribute | | 1 | `MODELS_REVERSE_COLUMN_MAP` | attribute => column |
- **`Phalcon\Mvc\Model\MetaData`** — implements [`Phalcon\Di\InjectionAwareInterface`](phalcon_di.md#diinjectionawareinterface), [`Phalcon\Mvc\Model\MetaDataInterface`](#mvcmodelmetadatainterface) - [`Phalcon\Mvc\Model\MetaData\Apcu`](#mvcmodelmetadataapcu) - [`Phalcon\Mvc\Model\MetaData\Libmemcached`](#mvcmodelmetadatalibmemcached) - [`Phalcon\Mvc\Model\MetaData\Memory`](#mvcmodelmetadatamemory) - [`Phalcon\Mvc\Model\MetaData\Redis`](#mvcmodelmetadataredis) - [`Phalcon\Mvc\Model\MetaData\Stream`](#mvcmodelmetadatastream)
__Uses__ `Phalcon\Cache\Adapter\AdapterInterface` · `Phalcon\Di\DiInterface` · `Phalcon\Di\InjectionAwareInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\MetaData\Exceptions\ContainerRequired` · `Phalcon\Mvc\Model\MetaData\Exceptions\CorruptedMetaData` · `Phalcon\Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel` · `Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed` · `Phalcon\Mvc\Model\MetaData\Strategy\Introspection` · `Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface` · `Phalcon\Support\Settings` { .api-uses } ### Method Summary
public CacheAdapterInterface|null getAdapter() Return the internal cache adapter public array getAttributes( ModelInterface $model ) Returns table attributes names (fields) public array getAutomaticCreateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the INSERT SQL generation public array getAutomaticUpdateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the UPDATE SQL generation public array getBindTypes( ModelInterface $model ) Returns attributes and their bind data types public array|null getColumnMap( ModelInterface $model ) Returns the column map if any public string|null getColumnMapUniqueKey( ModelInterface $model ) Returns a ColumnMap Unique key for meta-data is created using className public DiInterface getDI() Returns the DependencyInjector container public array getDataTypes( ModelInterface $model ) Returns attributes and their data types public array getDataTypesNumeric( ModelInterface $model ) Returns attributes which types are numerical public array getDefaultValues( ModelInterface $model ) Returns attributes (which have default values) and their default values public array getEmptyStringAttributes( ModelInterface $model ) Returns attributes allow empty strings public bool|string|null getIdentityField( ModelInterface $model ) Returns the name of identity field (if one is present) public string|null getMetaDataUniqueKey( ModelInterface $model ) Returns a MetaData Unique key for meta-data is created using className public string|null getModelUUID(ModelInterface $model,array $row) Returns the model UniqueID based on model and array row primary key(s) value(s) public array getNonPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are not part of the primary key public array getNotNullAttributes( ModelInterface $model ) Returns an array of not null attributes public array getPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are part of the primary key public array|null getReverseColumnMap( ModelInterface $model ) Returns the reverse column map if any public StrategyInterface getStrategy() Return the strategy to obtain the meta-data public bool hasAttribute(ModelInterface $model,string $attribute) Check if a model has certain attribute public bool isEmpty() Checks if the internal meta-data container is empty public bool modelEquals(ModelInterface $first,ModelInterface $other) Compares if two models are the same in memory public array|null read( mixed $key ) Reads metadata from the adapter public array|null readColumnMap( ModelInterface $model ) Reads the ordered/reversed column map for certain model public array|null readColumnMapIndex(ModelInterface $model,int $index) Reads column-map information for certain model using a MODEL_* constant public array|null readMetaData( ModelInterface $model ) Reads the complete meta-data for certain model public array|string|null readMetaDataIndex(ModelInterface $model,int $index) Reads meta-data for certain model public void reset() Resets internal meta-data in order to regenerate it public void setAutomaticCreateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the INSERT SQL generation public void setAutomaticUpdateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the UPDATE SQL generation public void setDI( DiInterface $container ) Sets the DependencyInjector container public void setEmptyStringAttributes(ModelInterface $model,array $attributes) Set the attributes that allow empty string values public void setStrategy( StrategyInterface $strategy ) Set the meta-data extraction strategy public void write(string $key,array $data) Writes the metadata to adapter public void writeMetaDataIndex(ModelInterface $model,int $index,mixed $data) Writes meta-data for certain model using a MODEL_* constant protected mixed getArrVal(array $collection,mixed $index,mixed $defaultValue = null) @todo Remove this when we get traits protected initialize(ModelInterface $model,mixed $key,mixed $table,mixed $schema) Initialize old behaviour for compatability protected bool initializeColumnMap(ModelInterface $model,mixed $key) Initialize ColumnMap for a certain table protected bool initializeMetaData(ModelInterface $model,mixed $key) Initialize the metadata for certain table
### Constants
int MODELS_ATTRIBUTES = 0
int MODELS_AUTOMATIC_DEFAULT_INSERT = 10
int MODELS_AUTOMATIC_DEFAULT_UPDATE = 11
int MODELS_COLUMN_MAP = 0
int MODELS_DATA_TYPES = 4
int MODELS_DATA_TYPES_BIND = 9
int MODELS_DATA_TYPES_NUMERIC = 5
int MODELS_DATE_AT = 6
int MODELS_DATE_IN = 7
int MODELS_DEFAULT_VALUES = 12
int MODELS_EMPTY_STRING_VALUES = 13
int MODELS_IDENTITY_COLUMN = 8
int MODELS_NON_PRIMARY_KEY = 2
int MODELS_NOT_NULL = 3
int MODELS_PRIMARY_KEY = 1
int MODELS_REVERSE_COLUMN_MAP = 1
### Properties
protected CacheAdapterInterface|null $adapter = null
protected array $columnMap = []
protected DiInterface|null $container = null
protected array $metaData = []
protected array $pendingMetaDataWrites = [] Holds metadata index writes that arrived before the model's metadata was properly initialized (e.g. skipAttributes() called in a parent model's initialize() while the child's source had not yet been set). Applied inside initializeMetaData() after the real schema is loaded.
protected StrategyInterface|null $strategy = null
### Methods
Public · 36
#### `getAdapter()` { #mvcmodelmetadata-getadapter }
public function getAdapter(): CacheAdapterInterface|null;
Return the internal cache adapter #### `getAttributes()` { #mvcmodelmetadata-getattributes }
public function getAttributes( ModelInterface $model ): array;
Returns table attributes names (fields)
print_r(
    $metaData->getAttributes(
        new Robots()
    )
);
#### `getAutomaticCreateAttributes()` { #mvcmodelmetadata-getautomaticcreateattributes }
public function getAutomaticCreateAttributes( ModelInterface $model ): array;
Returns attributes that must be ignored from the INSERT SQL generation
print_r(
    $metaData->getAutomaticCreateAttributes(
        new Robots()
    )
);
#### `getAutomaticUpdateAttributes()` { #mvcmodelmetadata-getautomaticupdateattributes }
public function getAutomaticUpdateAttributes( ModelInterface $model ): array;
Returns attributes that must be ignored from the UPDATE SQL generation
print_r(
    $metaData->getAutomaticUpdateAttributes(
        new Robots()
    )
);
#### `getBindTypes()` { #mvcmodelmetadata-getbindtypes }
public function getBindTypes( ModelInterface $model ): array;
Returns attributes and their bind data types
print_r(
    $metaData->getBindTypes(
        new Robots()
    )
);
#### `getColumnMap()` { #mvcmodelmetadata-getcolumnmap }
public function getColumnMap( ModelInterface $model ): array|null;
Returns the column map if any
print_r(
    $metaData->getColumnMap(
        new Robots()
    )
);
#### `getColumnMapUniqueKey()` { #mvcmodelmetadata-getcolumnmapuniquekey }
public final function getColumnMapUniqueKey( ModelInterface $model ): string|null;
Returns a ColumnMap Unique key for meta-data is created using className #### `getDI()` { #mvcmodelmetadata-getdi }
public function getDI(): DiInterface;
Returns the DependencyInjector container #### `getDataTypes()` { #mvcmodelmetadata-getdatatypes }
public function getDataTypes( ModelInterface $model ): array;
Returns attributes and their data types
print_r(
    $metaData->getDataTypes(
        new Robots()
    )
);
#### `getDataTypesNumeric()` { #mvcmodelmetadata-getdatatypesnumeric }
public function getDataTypesNumeric( ModelInterface $model ): array;
Returns attributes which types are numerical
print_r(
    $metaData->getDataTypesNumeric(
        new Robots()
    )
);
#### `getDefaultValues()` { #mvcmodelmetadata-getdefaultvalues }
public function getDefaultValues( ModelInterface $model ): array;
Returns attributes (which have default values) and their default values
print_r(
    $metaData->getDefaultValues(
        new Robots()
    )
);
#### `getEmptyStringAttributes()` { #mvcmodelmetadata-getemptystringattributes }
public function getEmptyStringAttributes( ModelInterface $model ): array;
Returns attributes allow empty strings
print_r(
    $metaData->getEmptyStringAttributes(
        new Robots()
    )
);
#### `getIdentityField()` { #mvcmodelmetadata-getidentityfield }
public function getIdentityField( ModelInterface $model ): bool|string|null;
Returns the name of identity field (if one is present)
print_r(
    $metaData->getIdentityField(
        new Robots()
    )
);
#### `getMetaDataUniqueKey()` { #mvcmodelmetadata-getmetadatauniquekey }
public final function getMetaDataUniqueKey( ModelInterface $model ): string|null;
Returns a MetaData Unique key for meta-data is created using className #### `getModelUUID()` { #mvcmodelmetadata-getmodeluuid }
public function getModelUUID(
    ModelInterface $model,
    array $row
): string|null;
Returns the model UniqueID based on model and array row primary key(s) value(s) #### `getNonPrimaryKeyAttributes()` { #mvcmodelmetadata-getnonprimarykeyattributes }
public function getNonPrimaryKeyAttributes( ModelInterface $model ): array;
Returns an array of fields which are not part of the primary key
print_r(
    $metaData->getNonPrimaryKeyAttributes(
        new Robots()
    )
);
#### `getNotNullAttributes()` { #mvcmodelmetadata-getnotnullattributes }
public function getNotNullAttributes( ModelInterface $model ): array;
Returns an array of not null attributes
print_r(
    $metaData->getNotNullAttributes(
        new Robots()
    )
);
#### `getPrimaryKeyAttributes()` { #mvcmodelmetadata-getprimarykeyattributes }
public function getPrimaryKeyAttributes( ModelInterface $model ): array;
Returns an array of fields which are part of the primary key
print_r(
    $metaData->getPrimaryKeyAttributes(
        new Robots()
    )
);
#### `getReverseColumnMap()` { #mvcmodelmetadata-getreversecolumnmap }
public function getReverseColumnMap( ModelInterface $model ): array|null;
Returns the reverse column map if any
print_r(
    $metaData->getReverseColumnMap(
        new Robots()
    )
);
#### `getStrategy()` { #mvcmodelmetadata-getstrategy }
public function getStrategy(): StrategyInterface;
Return the strategy to obtain the meta-data #### `hasAttribute()` { #mvcmodelmetadata-hasattribute }
public function hasAttribute(
    ModelInterface $model,
    string $attribute
): bool;
Check if a model has certain attribute
var_dump(
    $metaData->hasAttribute(
        new Robots(),
        "name"
    )
);
#### `isEmpty()` { #mvcmodelmetadata-isempty }
public function isEmpty(): bool;
Checks if the internal meta-data container is empty
var_dump(
    $metaData->isEmpty()
);
#### `modelEquals()` { #mvcmodelmetadata-modelequals }
public function modelEquals(
    ModelInterface $first,
    ModelInterface $other
): bool;
Compares if two models are the same in memory #### `read()` { #mvcmodelmetadata-read }
public function read( mixed $key ): array|null;
Reads metadata from the adapter #### `readColumnMap()` { #mvcmodelmetadata-readcolumnmap }
final public function readColumnMap( ModelInterface $model ): array|null;
Reads the ordered/reversed column map for certain model
print_r(
    $metaData->readColumnMap(
        new Robots()
    )
);
#### `readColumnMapIndex()` { #mvcmodelmetadata-readcolumnmapindex }
final public function readColumnMapIndex(
    ModelInterface $model,
    int $index
): array|null;
Reads column-map information for certain model using a MODEL_* constant
print_r(
    $metaData->readColumnMapIndex(
        new Robots(),
        MetaData::MODELS_REVERSE_COLUMN_MAP
    )
);
#### `readMetaData()` { #mvcmodelmetadata-readmetadata }
final public function readMetaData( ModelInterface $model ): array|null;
Reads the complete meta-data for certain model
print_r(
    $metaData->readMetaData(
        new Robots()
    )
);
#### `readMetaDataIndex()` { #mvcmodelmetadata-readmetadataindex }
final public function readMetaDataIndex(
    ModelInterface $model,
    int $index
): array|string|null;
Reads meta-data for certain model
print_r(
    $metaData->readMetaDataIndex(
        new Robots(),
        0
    )
);
#### `reset()` { #mvcmodelmetadata-reset }
public function reset(): void;
Resets internal meta-data in order to regenerate it
$metaData->reset();
#### `setAutomaticCreateAttributes()` { #mvcmodelmetadata-setautomaticcreateattributes }
public function setAutomaticCreateAttributes(
    ModelInterface $model,
    array $attributes
): void;
Set the attributes that must be ignored from the INSERT SQL generation
$metaData->setAutomaticCreateAttributes(
    new Robots(),
    [
        "created_at" => true,
    ]
);
#### `setAutomaticUpdateAttributes()` { #mvcmodelmetadata-setautomaticupdateattributes }
public function setAutomaticUpdateAttributes(
    ModelInterface $model,
    array $attributes
): void;
Set the attributes that must be ignored from the UPDATE SQL generation
$metaData->setAutomaticUpdateAttributes(
    new Robots(),
    [
        "modified_at" => true,
    ]
);
#### `setDI()` { #mvcmodelmetadata-setdi }
public function setDI( DiInterface $container ): void;
Sets the DependencyInjector container #### `setEmptyStringAttributes()` { #mvcmodelmetadata-setemptystringattributes }
public function setEmptyStringAttributes(
    ModelInterface $model,
    array $attributes
): void;
Set the attributes that allow empty string values
$metaData->setEmptyStringAttributes(
    new Robots(),
    [
        "name" => true,
    ]
);
#### `setStrategy()` { #mvcmodelmetadata-setstrategy }
public function setStrategy( StrategyInterface $strategy ): void;
Set the meta-data extraction strategy #### `write()` { #mvcmodelmetadata-write }
public function write(
    string $key,
    array $data
): void;
Writes the metadata to adapter #### `writeMetaDataIndex()` { #mvcmodelmetadata-writemetadataindex }
final public function writeMetaDataIndex(
    ModelInterface $model,
    int $index,
    mixed $data
): void;
Writes meta-data for certain model using a MODEL_* constant
print_r(
    $metaData->writeColumnMapIndex(
        new Robots(),
        MetaData::MODELS_REVERSE_COLUMN_MAP,
        [
            "leName" => "name",
        ]
    )
);
Protected · 4
#### `getArrVal()` { #mvcmodelmetadata-getarrval }
protected function getArrVal(
    array $collection,
    mixed $index,
    mixed $defaultValue = null
): mixed;
@todo Remove this when we get traits #### `initialize()` { #mvcmodelmetadata-initialize }
final protected function initialize(
    ModelInterface $model,
    mixed $key,
    mixed $table,
    mixed $schema
);
Initialize old behaviour for compatability #### `initializeColumnMap()` { #mvcmodelmetadata-initializecolumnmap }
final protected function initializeColumnMap(
    ModelInterface $model,
    mixed $key
): bool;
Initialize ColumnMap for a certain table #### `initializeMetaData()` { #mvcmodelmetadata-initializemetadata }
final protected function initializeMetaData(
    ModelInterface $model,
    mixed $key
): bool;
Initialize the metadata for certain table ## Mvc\Model\MetaDataInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaDataInterface.zep){ .src-btn } Phalcon\Mvc\Model\MetaDataInterface Interface for Phalcon\Mvc\Model\MetaData
- **`Phalcon\Mvc\Model\MetaDataInterface`**
__Uses__ `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface` { .api-uses } ### Method Summary
public array getAttributes( ModelInterface $model ) Returns table attributes names (fields) public array getAutomaticCreateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the INSERT SQL generation public array getAutomaticUpdateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the UPDATE SQL generation public array getBindTypes( ModelInterface $model ) Returns attributes and their bind data types public array|null getColumnMap( ModelInterface $model ) Returns the column map if any public array getDataTypes( ModelInterface $model ) Returns attributes and their data types public array getDataTypesNumeric( ModelInterface $model ) Returns attributes which types are numerical public array getDefaultValues( ModelInterface $model ) Returns attributes (which have default values) and their default values public array getEmptyStringAttributes( ModelInterface $model ) Returns attributes allow empty strings public bool|string|null getIdentityField( ModelInterface $model ) Returns the name of identity field (if one is present) public array getNonPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are not part of the primary key public array getNotNullAttributes( ModelInterface $model ) Returns an array of not null attributes public array getPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are part of the primary key public array|null getReverseColumnMap( ModelInterface $model ) Returns the reverse column map if any public StrategyInterface getStrategy() Return the strategy to obtain the meta-data public bool hasAttribute(ModelInterface $model,string $attribute) Check if a model has certain attribute public bool isEmpty() Checks if the internal meta-data container is empty public array|null read( string $key ) Reads meta-data from the adapter public array|null readColumnMap( ModelInterface $model ) Reads the ordered/reversed column map for certain model public array|null readColumnMapIndex(ModelInterface $model,int $index) Reads column-map information for certain model using a MODEL_* constant public array|null readMetaData( ModelInterface $model ) Reads meta-data for certain model public array|string|null readMetaDataIndex(ModelInterface $model,int $index) Reads meta-data for certain model using a MODEL_* constant public reset() Resets internal meta-data in order to regenerate it public setAutomaticCreateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the INSERT SQL generation public setAutomaticUpdateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the UPDATE SQL generation public void setEmptyStringAttributes(ModelInterface $model,array $attributes) Set the attributes that allow empty string values public setStrategy( StrategyInterface $strategy ) Set the meta-data extraction strategy public void write(string $key,array $data) Writes meta-data to the adapter public writeMetaDataIndex(ModelInterface $model,int $index,mixed $data) Writes meta-data for certain model using a MODEL_* constant
### Methods
Public · 29
#### `getAttributes()` { #mvcmodelmetadatainterface-getattributes }
public function getAttributes( ModelInterface $model ): array;
Returns table attributes names (fields) #### `getAutomaticCreateAttributes()` { #mvcmodelmetadatainterface-getautomaticcreateattributes }
public function getAutomaticCreateAttributes( ModelInterface $model ): array;
Returns attributes that must be ignored from the INSERT SQL generation #### `getAutomaticUpdateAttributes()` { #mvcmodelmetadatainterface-getautomaticupdateattributes }
public function getAutomaticUpdateAttributes( ModelInterface $model ): array;
Returns attributes that must be ignored from the UPDATE SQL generation #### `getBindTypes()` { #mvcmodelmetadatainterface-getbindtypes }
public function getBindTypes( ModelInterface $model ): array;
Returns attributes and their bind data types #### `getColumnMap()` { #mvcmodelmetadatainterface-getcolumnmap }
public function getColumnMap( ModelInterface $model ): array|null;
Returns the column map if any #### `getDataTypes()` { #mvcmodelmetadatainterface-getdatatypes }
public function getDataTypes( ModelInterface $model ): array;
Returns attributes and their data types #### `getDataTypesNumeric()` { #mvcmodelmetadatainterface-getdatatypesnumeric }
public function getDataTypesNumeric( ModelInterface $model ): array;
Returns attributes which types are numerical #### `getDefaultValues()` { #mvcmodelmetadatainterface-getdefaultvalues }
public function getDefaultValues( ModelInterface $model ): array;
Returns attributes (which have default values) and their default values #### `getEmptyStringAttributes()` { #mvcmodelmetadatainterface-getemptystringattributes }
public function getEmptyStringAttributes( ModelInterface $model ): array;
Returns attributes allow empty strings #### `getIdentityField()` { #mvcmodelmetadatainterface-getidentityfield }
public function getIdentityField( ModelInterface $model ): bool|string|null;
Returns the name of identity field (if one is present) #### `getNonPrimaryKeyAttributes()` { #mvcmodelmetadatainterface-getnonprimarykeyattributes }
public function getNonPrimaryKeyAttributes( ModelInterface $model ): array;
Returns an array of fields which are not part of the primary key #### `getNotNullAttributes()` { #mvcmodelmetadatainterface-getnotnullattributes }
public function getNotNullAttributes( ModelInterface $model ): array;
Returns an array of not null attributes #### `getPrimaryKeyAttributes()` { #mvcmodelmetadatainterface-getprimarykeyattributes }
public function getPrimaryKeyAttributes( ModelInterface $model ): array;
Returns an array of fields which are part of the primary key #### `getReverseColumnMap()` { #mvcmodelmetadatainterface-getreversecolumnmap }
public function getReverseColumnMap( ModelInterface $model ): array|null;
Returns the reverse column map if any #### `getStrategy()` { #mvcmodelmetadatainterface-getstrategy }
public function getStrategy(): StrategyInterface;
Return the strategy to obtain the meta-data #### `hasAttribute()` { #mvcmodelmetadatainterface-hasattribute }
public function hasAttribute(
    ModelInterface $model,
    string $attribute
): bool;
Check if a model has certain attribute #### `isEmpty()` { #mvcmodelmetadatainterface-isempty }
public function isEmpty(): bool;
Checks if the internal meta-data container is empty #### `read()` { #mvcmodelmetadatainterface-read }
public function read( string $key ): array|null;
Reads meta-data from the adapter #### `readColumnMap()` { #mvcmodelmetadatainterface-readcolumnmap }
public function readColumnMap( ModelInterface $model ): array|null;
Reads the ordered/reversed column map for certain model #### `readColumnMapIndex()` { #mvcmodelmetadatainterface-readcolumnmapindex }
public function readColumnMapIndex(
    ModelInterface $model,
    int $index
): array|null;
Reads column-map information for certain model using a MODEL_* constant #### `readMetaData()` { #mvcmodelmetadatainterface-readmetadata }
public function readMetaData( ModelInterface $model ): array|null;
Reads meta-data for certain model #### `readMetaDataIndex()` { #mvcmodelmetadatainterface-readmetadataindex }
public function readMetaDataIndex(
    ModelInterface $model,
    int $index
): array|string|null;
Reads meta-data for certain model using a MODEL_* constant #### `reset()` { #mvcmodelmetadatainterface-reset }
public function reset();
Resets internal meta-data in order to regenerate it #### `setAutomaticCreateAttributes()` { #mvcmodelmetadatainterface-setautomaticcreateattributes }
public function setAutomaticCreateAttributes(
    ModelInterface $model,
    array $attributes
);
Set the attributes that must be ignored from the INSERT SQL generation #### `setAutomaticUpdateAttributes()` { #mvcmodelmetadatainterface-setautomaticupdateattributes }
public function setAutomaticUpdateAttributes(
    ModelInterface $model,
    array $attributes
);
Set the attributes that must be ignored from the UPDATE SQL generation #### `setEmptyStringAttributes()` { #mvcmodelmetadatainterface-setemptystringattributes }
public function setEmptyStringAttributes(
    ModelInterface $model,
    array $attributes
): void;
Set the attributes that allow empty string values #### `setStrategy()` { #mvcmodelmetadatainterface-setstrategy }
public function setStrategy( StrategyInterface $strategy );
Set the meta-data extraction strategy #### `write()` { #mvcmodelmetadatainterface-write }
public function write(
    string $key,
    array $data
): void;
Writes meta-data to the adapter #### `writeMetaDataIndex()` { #mvcmodelmetadatainterface-writemetadataindex }
public function writeMetaDataIndex(
    ModelInterface $model,
    int $index,
    mixed $data
);
Writes meta-data for certain model using a MODEL_* constant ## Mvc\Model\MetaData\Apcu Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Apcu.zep){ .src-btn } Phalcon\Mvc\Model\MetaData\Apcu Stores model meta-data in the APCu cache. Data will erased if the web server is restarted By default meta-data is stored for 48 hours (172800 seconds) You can query the meta-data by printing apcu_fetch('$PMM$') or apcu_fetch('$PMM$my-app-id')
$metaData = new \Phalcon\Mvc\Model\MetaData\Apcu(
    [
        "prefix"   => "my-app-id",
        "lifetime" => 86400,
    ]
);
- [`Phalcon\Mvc\Model\MetaData`](#mvcmodelmetadata) - **`Phalcon\Mvc\Model\MetaData\Apcu`**
__Uses__ `Phalcon\Cache\AdapterFactory` · `Phalcon\Mvc\Model\MetaData` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataapcu-__construct }
public function __construct(
    AdapterFactory $factory,
    array $options = null
);
Phalcon\Mvc\Model\MetaData\Apcu constructor ## Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/CannotObtainTableColumns.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionscannotobtaintablecolumns-__construct }
public function __construct(
    string $completeTable,
    string $className
);
## Mvc\Model\MetaData\Exceptions\ColumnMapNotArray Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/ColumnMapNotArray.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\ColumnMapNotArray`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionscolumnmapnotarray-__construct }
public function __construct();
## Mvc\Model\MetaData\Exceptions\ContainerRequired Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/ContainerRequired.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\ContainerRequired`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionscontainerrequired-__construct }
public function __construct();
## Mvc\Model\MetaData\Exceptions\CorruptedMetaData Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/CorruptedMetaData.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\CorruptedMetaData`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionscorruptedmetadata-__construct }
public function __construct();
## Mvc\Model\MetaData\Exceptions\InvalidContainer Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/InvalidContainer.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\InvalidContainer`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionsinvalidcontainer-__construct }
public function __construct();
## Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/InvalidMetaDataForModel.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionsinvalidmetadataformodel-__construct }
public function __construct( string $modelName );
## Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/MetaDataDirectoryNotWritable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionsmetadatadirectorynotwritable-__construct }
public function __construct();
## Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/MetaDataStrategyFailed.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionsmetadatastrategyfailed-__construct }
public function __construct( string $message );
## Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/NoAnnotationsForClass.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionsnoannotationsforclass-__construct }
public function __construct( string $className );
## Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/NoPropertyAnnotationsForClass.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionsnopropertyannotationsforclass-__construct }
public function __construct( string $className );
## Mvc\Model\MetaData\Exceptions\TableNotInDatabase Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Exceptions/TableNotInDatabase.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\MetaData\Exceptions\TableNotInDatabase`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelmetadataexceptionstablenotindatabase-__construct }
public function __construct(
    string $completeTable,
    string $className
);
## Mvc\Model\MetaData\Libmemcached Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Libmemcached.zep){ .src-btn } Phalcon\Mvc\Model\MetaData\Libmemcached Stores model meta-data in the Memcache. By default meta-data is stored for 48 hours (172800 seconds)
- [`Phalcon\Mvc\Model\MetaData`](#mvcmodelmetadata) - **`Phalcon\Mvc\Model\MetaData\Libmemcached`**
__Uses__ `Phalcon\Cache\AdapterFactory` · `Phalcon\Mvc\Model\MetaData` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `__construct()` { #mvcmodelmetadatalibmemcached-__construct }
public function __construct(
    AdapterFactory $factory,
    array $options = []
);
Phalcon\Mvc\Model\MetaData\Libmemcached constructor #### `reset()` { #mvcmodelmetadatalibmemcached-reset }
public function reset(): void;
Flush Memcache data and resets internal meta-data in order to regenerate it ## Mvc\Model\MetaData\Memory Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Memory.zep){ .src-btn } Phalcon\Mvc\Model\MetaData\Memory Stores model meta-data in memory. Data will be erased when the request finishes
- [`Phalcon\Mvc\Model\MetaData`](#mvcmodelmetadata) - **`Phalcon\Mvc\Model\MetaData\Memory`**
__Uses__ `Phalcon\Mvc\Model\MetaData` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `read()` { #mvcmodelmetadatamemory-read }
public function read( mixed $key ): array|null;
Reads the meta-data from temporal memory #### `write()` { #mvcmodelmetadatamemory-write }
public function write(
    mixed $key,
    array $data
): void;
Writes the meta-data to temporal memory ## Mvc\Model\MetaData\Redis Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Redis.zep){ .src-btn } Phalcon\Mvc\Model\MetaData\Redis Stores model meta-data in the Redis. By default meta-data is stored for 48 hours (172800 seconds)
use Phalcon\Mvc\Model\MetaData\Redis;

$metaData = new Redis(
    [
        "host"       => "127.0.0.1",
        "port"       => 6379,
        "persistent" => 0,
        "lifetime"   => 172800,
        "index"      => 2,
    ]
);
- [`Phalcon\Mvc\Model\MetaData`](#mvcmodelmetadata) - **`Phalcon\Mvc\Model\MetaData\Redis`**
__Uses__ `Phalcon\Cache\AdapterFactory` · `Phalcon\Mvc\Model\MetaData` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `__construct()` { #mvcmodelmetadataredis-__construct }
public function __construct(
    AdapterFactory $factory,
    array $options = []
);
Phalcon\Mvc\Model\MetaData\Redis constructor #### `reset()` { #mvcmodelmetadataredis-reset }
public function reset(): void;
Flush Redis data and resets internal meta-data in order to regenerate it ## Mvc\Model\MetaData\Strategy\Annotations Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Strategy/Annotations.zep){ .src-btn }
- **`Phalcon\Mvc\Model\MetaData\Strategy\Annotations`** — implements [`Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface`](#mvcmodelmetadatastrategystrategyinterface)
__Uses__ `Phalcon\Db\Column` · `Phalcon\Di\DiInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\MetaData` · `Phalcon\Mvc\Model\MetaData\Exceptions\InvalidContainer` · `Phalcon\Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass` · `Phalcon\Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `getColumnMaps()` { #mvcmodelmetadatastrategyannotations-getcolumnmaps }
final public function getColumnMaps(
    ModelInterface $model,
    DiInterface $container
): array;
Read the model's column map, this can't be inferred #### `getMetaData()` { #mvcmodelmetadatastrategyannotations-getmetadata }
final public function getMetaData(
    ModelInterface $model,
    DiInterface $container
): array;
The meta-data is obtained by reading the column descriptions from the database information schema ## Mvc\Model\MetaData\Strategy\Introspection Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Strategy/Introspection.zep){ .src-btn } Queries the table meta-data in order to introspect the model's metadata
- **`Phalcon\Mvc\Model\MetaData\Strategy\Introspection`** — implements [`Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface`](#mvcmodelmetadatastrategystrategyinterface)
__Uses__ `Phalcon\Db\Adapter\AdapterInterface` · `Phalcon\Di\DiInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\MetaData` · `Phalcon\Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns` · `Phalcon\Mvc\Model\MetaData\Exceptions\ColumnMapNotArray` · `Phalcon\Mvc\Model\MetaData\Exceptions\TableNotInDatabase` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `getColumnMaps()` { #mvcmodelmetadatastrategyintrospection-getcolumnmaps }
final public function getColumnMaps(
    ModelInterface $model,
    DiInterface $container
): array;
Read the model's column map, this can't be inferred #### `getMetaData()` { #mvcmodelmetadatastrategyintrospection-getmetadata }
final public function getMetaData(
    ModelInterface $model,
    DiInterface $container
): array;
The meta-data is obtained by reading the column descriptions from the database information schema ## Mvc\Model\MetaData\Strategy\StrategyInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Strategy/StrategyInterface.zep){ .src-btn }
- **`Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface`**
__Uses__ `Phalcon\Di\DiInterface` · `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `getColumnMaps()` { #mvcmodelmetadatastrategystrategyinterface-getcolumnmaps }
public function getColumnMaps(
    ModelInterface $model,
    DiInterface $container
): array;
Read the model's column map, this can't be inferred @todo Not implemented #### `getMetaData()` { #mvcmodelmetadatastrategystrategyinterface-getmetadata }
public function getMetaData(
    ModelInterface $model,
    DiInterface $container
): array;
The meta-data is obtained by reading the column descriptions from the database information schema ## Mvc\Model\MetaData\Stream Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/MetaData/Stream.zep){ .src-btn } Phalcon\Mvc\Model\MetaData\Stream Stores model meta-data in PHP files.
$metaData = new \Phalcon\Mvc\Model\MetaData\Files(
    [
        "metaDataDir" => "app/cache/metadata/",
    ]
);
- [`Phalcon\Mvc\Model\MetaData`](#mvcmodelmetadata) - **`Phalcon\Mvc\Model\MetaData\Stream`**
__Uses__ `Phalcon\Mvc\Model\MetaData` · `Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable` · `Phalcon\Support\Settings` { .api-uses } ### Method Summary ### Properties
protected string $metaDataDir = "./"
### Methods
Public · 3
#### `__construct()` { #mvcmodelmetadatastream-__construct }
public function __construct( array $options = [] );
Phalcon\Mvc\Model\MetaData\Files constructor #### `read()` { #mvcmodelmetadatastream-read }
public function read( mixed $key ): array|null;
Reads meta-data from files #### `write()` { #mvcmodelmetadatastream-write }
public function write(
    mixed $key,
    array $data
): void;
Writes the meta-data to files ## Mvc\Model\Query Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query.zep){ .src-btn } Phalcon\Mvc\Model\Query This class takes a PHQL intermediate representation and executes it.
$phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b
         WHERE b.name = :name: ORDER BY c.name";

$result = $manager->executeQuery(
    $phql,
    [
        "name" => "Lamborghini",
    ]
);

foreach ($result as $row) {
    echo "Name: ",  $row->cars->name, "\n";
    echo "Price: ", $row->cars->price, "\n";
    echo "Taxes: ", $row->taxes, "\n";
}

// with transaction
use Phalcon\Mvc\Model\Query;
use Phalcon\Mvc\Model\Transaction;

// $di needs to have the service "db" registered for this to work
$di = Phalcon\Di\FactoryDefault::getDefault();

$phql = 'SELECT * FROM robot';

$myTransaction = new Transaction($di);
$myTransaction->begin();

$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->type = "mechanical";
$newRobot->name = "Astro Boy";
$newRobot->year = 1952;
$newRobot->save();

$queryWithTransaction = new Query($phql, $di);
$queryWithTransaction->setTransaction($myTransaction);

$resultWithEntries = $queryWithTransaction->execute();

$queryWithOutTransaction = new Query($phql, $di);
$resultWithOutEntries = $queryWithTransaction->execute();
- **`Phalcon\Mvc\Model\Query`** — implements [`Phalcon\Mvc\Model\QueryInterface`](#mvcmodelqueryinterface), [`Phalcon\Di\InjectionAwareInterface`](phalcon_di.md#diinjectionawareinterface)
__Uses__ `Phalcon\Db\Adapter\AdapterInterface` · `Phalcon\Db\Column` · `Phalcon\Db\DialectInterface` · `Phalcon\Db\RawValue` · `Phalcon\Db\ResultInterface` · `Phalcon\Di\DiInterface` · `Phalcon\Di\InjectionAwareInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Query\Exceptions\AmbiguousColumn` · `Phalcon\Mvc\Model\Query\Exceptions\AmbiguousJoinRelation` · `Phalcon\Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders` · `Phalcon\Mvc\Model\Query\Exceptions\BindTypeRequiresArray` · `Phalcon\Mvc\Model\Query\Exceptions\BindValueRequired` · `Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInDomain` · `Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels` · `Phalcon\Mvc\Model\Query\Exceptions\CorruptedAst` · `Phalcon\Mvc\Model\Query\Exceptions\CorruptedDeleteAst` · `Phalcon\Mvc\Model\Query\Exceptions\CorruptedInsertAst` · `Phalcon\Mvc\Model\Query\Exceptions\CorruptedSelectAst` · `Phalcon\Mvc\Model\Query\Exceptions\CorruptedUpdateAst` · `Phalcon\Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported` · `Phalcon\Mvc\Model\Query\Exceptions\DuplicateAlias` · `Phalcon\Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue` · `Phalcon\Mvc\Model\Query\Exceptions\InsertColumnCountMismatch` · `Phalcon\Mvc\Model\Query\Exceptions\InvalidCachedResultset` · `Phalcon\Mvc\Model\Query\Exceptions\InvalidCachingOptions` · `Phalcon\Mvc\Model\Query\Exceptions\InvalidColumnDefinition` · `Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedManager` · `Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedMetadata` · `Phalcon\Mvc\Model\Query\Exceptions\InvalidQueryCacheService` · `Phalcon\Mvc\Model\Query\Exceptions\InvalidResultsetClass` · `Phalcon\Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed` · `Phalcon\Mvc\Model\Query\Exceptions\JoinFieldCountMismatch` · `Phalcon\Mvc\Model\Query\Exceptions\MissingCacheKey` · `Phalcon\Mvc\Model\Query\Exceptions\MissingMetaData` · `Phalcon\Mvc\Model\Query\Exceptions\MissingModelAttribute` · `Phalcon\Mvc\Model\Query\Exceptions\MissingModelsManager` · `Phalcon\Mvc\Model\Query\Exceptions\MixedDatabaseSystems` · `Phalcon\Mvc\Model\Query\Exceptions\ModelSourceNotFound` · `Phalcon\Mvc\Model\Query\Exceptions\ModelsListNotLoaded` · `Phalcon\Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported` · `Phalcon\Mvc\Model\Query\Exceptions\NoModelForAlias` · `Phalcon\Mvc\Model\Query\Exceptions\PhqlColumnNotInMap` · `Phalcon\Mvc\Model\Query\Exceptions\ReadConnectionMissing` · `Phalcon\Mvc\Model\Query\Exceptions\RelationshipNotFound` · `Phalcon\Mvc\Model\Query\Exceptions\ResultsetClassNotFound` · `Phalcon\Mvc\Model\Query\Exceptions\ResultsetNonCacheable` · `Phalcon\Mvc\Model\Query\Exceptions\UnknownBindType` · `Phalcon\Mvc\Model\Query\Exceptions\UnknownColumnType` · `Phalcon\Mvc\Model\Query\Exceptions\UnknownJoinType` · `Phalcon\Mvc\Model\Query\Exceptions\UnknownModelOrAlias` · `Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpression` · `Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType` · `Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlStatement` · `Phalcon\Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported` · `Phalcon\Mvc\Model\Query\Exceptions\WriteConnectionMissing` · `Phalcon\Mvc\Model\Query\Lang` · `Phalcon\Mvc\Model\Query\Status` · `Phalcon\Mvc\Model\Query\StatusInterface` · `Phalcon\Mvc\Model\ResultsetInterface` · `Phalcon\Mvc\Model\Resultset\Complex` · `Phalcon\Mvc\Model\Resultset\Simple` · `Phalcon\Support\Settings` { .api-uses } ### Method Summary
public __construct(string $phql = null,DiInterface $container = null,array $options = []) Phalcon\Mvc\Model\Query constructor public QueryInterface cache( array $cacheOptions ) Sets the cache parameters of the query public void clean() Destroys the internal PHQL cache public execute(array $bindParams = [],array $bindTypes = []) Executes a parsed PHQL statement public array getBindParams() Returns default bind params public array getBindTypes() Returns default bind types public AdapterInterface getCache() Returns the current cache backend instance public array getCacheOptions() Returns the current cache options public DiInterface getDI() Returns the dependency injection container public array getIntermediate() Returns the intermediate representation of the PHQL statement public ModelInterface getSingleResult(array $bindParams = [],array $bindTypes = []) Executes the query returning the first result public array getSql() Returns an associative array with the SQL to be generated by the internal PHQL, public TransactionInterface|null getTransaction() public int getType() Gets the type of PHQL statement executed public bool getUniqueRow() Check if the query is programmed to get only the first row in the public array parse() Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang public QueryInterface setBindParams(array $bindParams,bool $merge = false) Set default bind parameters public QueryInterface setBindTypes(array $bindTypes,bool $merge = false) Set default bind parameters public void setDI( DiInterface $container ) Sets the dependency injection container public QueryInterface setIntermediate( array $intermediate ) Allows to set the IR to be executed public QueryInterface setSharedLock( bool $sharedLock = false ) Set SHARED LOCK clause public QueryInterface setTransaction( TransactionInterface $transaction ) allows to wrap a transaction around all queries public QueryInterface setType( int $type ) Sets the type of PHQL statement to be executed public QueryInterface setUniqueRow( bool $uniqueRow ) Tells to the query if only the first row in the resultset must be protected StatusInterface executeDelete(array $intermediate,array $bindParams,array $bindTypes) Executes the DELETE intermediate representation producing a protected StatusInterface executeInsert(array $intermediate,array $bindParams,array $bindTypes) Executes the INSERT intermediate representation producing a protected ResultsetInterface|array executeSelect(array $intermediate,array $bindParams,array $bindTypes,bool $simulate = false) Executes the SELECT intermediate representation producing a protected StatusInterface executeUpdate(array $intermediate,array $bindParams,array $bindTypes) Executes the UPDATE intermediate representation producing a protected array getCallArgument( array $argument ) Resolves an expression in a single call argument protected array getCaseExpression( array $expr ) Resolves an expression in a single call argument protected array getExpression(array $expr,bool $quoting = true) Resolves an expression from its intermediate code into an array protected array getFunctionCall( array $expr ) Resolves an expression in a single call argument protected array getGroupClause( array $group ) Returns a processed group clause for a SELECT statement protected array getJoin(ManagerInterface $manager,array $join) Resolves a JOIN clause checking if the associated models exist protected string getJoinType( array $join ) Resolves a JOIN type protected array getJoins( array $select ) Processes the JOINs in the query returning an internal representation for protected array getLimitClause( array $limitClause ) Returns a processed limit clause for a SELECT statement protected array getMultiJoin(string $joinType,mixed $joinSource,string $modelAlias,string $joinAlias,RelationInterface $relation) Resolves joins involving many-to-many relations protected array getOrderClause( mixed $order ) Returns a processed order clause for a SELECT statement protected array getQualified( array $expr ) Replaces the model's name to its source name in a qualified-name protected AdapterInterface getReadConnection(ModelInterface $model,array $intermediate = null,array $bindParams = [],array $bindTypes = []) Gets the read connection from the model if there is no transaction set protected ResultsetInterface getRelatedRecords(ModelInterface $model,array $intermediate,array $bindParams,array $bindTypes) Query the records on which the UPDATE/DELETE operation will be done protected array getSelectColumn( array $column ) Resolves a column from its intermediate representation into an array protected array getSingleJoin(string $joinType,mixed $joinSource,string $modelAlias,string $joinAlias,RelationInterface $relation) Resolves joins involving has-one/belongs-to/has-many relations protected getTable(ManagerInterface $manager,array $qualifiedName) Resolves a table in a SELECT statement checking if the model exists protected AdapterInterface getWriteConnection(ModelInterface $model,array $intermediate = null,array $bindParams = [],array $bindTypes = []) Gets the write connection from the model if there is no transaction protected array prepareDelete() Analyzes a DELETE intermediate code and produces an array to be executed protected array prepareInsert() Analyzes an INSERT intermediate code and produces an array to be executed protected array prepareSelect(mixed $ast = null,bool $merge = false) Analyzes a SELECT intermediate code and produces an array to be executed later protected array prepareUpdate() Analyzes an UPDATE intermediate code and produces an array to be executed protected array refreshSchemasInIntermediate( array $irPhql ) Refreshes the schema/source of every model referenced in a cached
### Constants
int TYPE_DELETE = 303
int TYPE_INSERT = 306
int TYPE_SELECT = 309
int TYPE_UPDATE = 300
### Properties
protected array $ast
protected array $bindParams = []
protected array $bindTypes = []
protected mixed|null $cache = null
protected array|null $cacheOptions
protected DiInterface|null $container = null
protected bool $enableImplicitJoins
protected array $intermediate
protected array|null $internalPhqlCache
protected \Phalcon\Mvc\Model\ManagerInterface|null $manager = null
protected \Phalcon\Mvc\Model\MetaDataInterface|null $metaData = null
protected array $models = []
protected array $modelsInstances = []
protected int $nestingLevel = -1
protected string|null $phql = null
protected bool $sharedLock = false
protected array $sqlAliases = []
protected array $sqlAliasesModels = []
protected array $sqlAliasesModelsInstances = []
protected array $sqlColumnAliases = []
protected array $sqlModelsAliases = []
protected TransactionInterface|null $transaction = null TransactionInterface so that the query can wrap a transaction around batch updates and intermediate selects within the transaction. however if a model got a transaction set inside it will use the local transaction instead of this one
protected int|null $type
protected bool $uniqueRow = false
### Methods
Public · 24
#### `__construct()` { #mvcmodelquery-__construct }
public function __construct(
    string $phql = null,
    DiInterface $container = null,
    array $options = []
);
Phalcon\Mvc\Model\Query constructor #### `cache()` { #mvcmodelquery-cache }
public function cache( array $cacheOptions ): QueryInterface;
Sets the cache parameters of the query #### `clean()` { #mvcmodelquery-clean }
public static function clean(): void;
Destroys the internal PHQL cache #### `execute()` { #mvcmodelquery-execute }
public function execute(
    array $bindParams = [],
    array $bindTypes = []
);
Executes a parsed PHQL statement #### `getBindParams()` { #mvcmodelquery-getbindparams }
public function getBindParams(): array;
Returns default bind params #### `getBindTypes()` { #mvcmodelquery-getbindtypes }
public function getBindTypes(): array;
Returns default bind types #### `getCache()` { #mvcmodelquery-getcache }
public function getCache(): AdapterInterface;
Returns the current cache backend instance #### `getCacheOptions()` { #mvcmodelquery-getcacheoptions }
public function getCacheOptions(): array;
Returns the current cache options #### `getDI()` { #mvcmodelquery-getdi }
public function getDI(): DiInterface;
Returns the dependency injection container #### `getIntermediate()` { #mvcmodelquery-getintermediate }
public function getIntermediate(): array;
Returns the intermediate representation of the PHQL statement #### `getSingleResult()` { #mvcmodelquery-getsingleresult }
public function getSingleResult(
    array $bindParams = [],
    array $bindTypes = []
): ModelInterface;
Executes the query returning the first result #### `getSql()` { #mvcmodelquery-getsql }
public function getSql(): array;
Returns an associative array with the SQL to be generated by the internal PHQL, and arrays with bound parameters and their types (only works in SELECT statements).
[
    'sql' => 'SELECT * FROM parts WHERE robot = :robot',
    'bind' => ['robot' => 123],
    'bindTypes => ['robot' => 1] // 1 corresponds to int
]
#### `getTransaction()` { #mvcmodelquery-gettransaction }
public function getTransaction(): TransactionInterface|null;
#### `getType()` { #mvcmodelquery-gettype }
public function getType(): int;
Gets the type of PHQL statement executed #### `getUniqueRow()` { #mvcmodelquery-getuniquerow }
public function getUniqueRow(): bool;
Check if the query is programmed to get only the first row in the resultset #### `parse()` { #mvcmodelquery-parse }
public function parse(): array;
Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query #### `setBindParams()` { #mvcmodelquery-setbindparams }
public function setBindParams(
    array $bindParams,
    bool $merge = false
): QueryInterface;
Set default bind parameters #### `setBindTypes()` { #mvcmodelquery-setbindtypes }
public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): QueryInterface;
Set default bind parameters #### `setDI()` { #mvcmodelquery-setdi }
public function setDI( DiInterface $container ): void;
Sets the dependency injection container #### `setIntermediate()` { #mvcmodelquery-setintermediate }
public function setIntermediate( array $intermediate ): QueryInterface;
Allows to set the IR to be executed #### `setSharedLock()` { #mvcmodelquery-setsharedlock }
public function setSharedLock( bool $sharedLock = false ): QueryInterface;
Set SHARED LOCK clause #### `setTransaction()` { #mvcmodelquery-settransaction }
public function setTransaction( TransactionInterface $transaction ): QueryInterface;
allows to wrap a transaction around all queries #### `setType()` { #mvcmodelquery-settype }
public function setType( int $type ): QueryInterface;
Sets the type of PHQL statement to be executed #### `setUniqueRow()` { #mvcmodelquery-setuniquerow }
public function setUniqueRow( bool $uniqueRow ): QueryInterface;
Tells to the query if only the first row in the resultset must be returned
Protected · 27
#### `executeDelete()` { #mvcmodelquery-executedelete }
final protected function executeDelete(
    array $intermediate,
    array $bindParams,
    array $bindTypes
): StatusInterface;
Executes the DELETE intermediate representation producing a Phalcon\Mvc\Model\Query\Status #### `executeInsert()` { #mvcmodelquery-executeinsert }
final protected function executeInsert(
    array $intermediate,
    array $bindParams,
    array $bindTypes
): StatusInterface;
Executes the INSERT intermediate representation producing a Phalcon\Mvc\Model\Query\Status #### `executeSelect()` { #mvcmodelquery-executeselect }
final protected function executeSelect(
    array $intermediate,
    array $bindParams,
    array $bindTypes,
    bool $simulate = false
): ResultsetInterface|array;
Executes the SELECT intermediate representation producing a Phalcon\Mvc\Model\Resultset #### `executeUpdate()` { #mvcmodelquery-executeupdate }
final protected function executeUpdate(
    array $intermediate,
    array $bindParams,
    array $bindTypes
): StatusInterface;
Executes the UPDATE intermediate representation producing a Phalcon\Mvc\Model\Query\Status #### `getCallArgument()` { #mvcmodelquery-getcallargument }
final protected function getCallArgument( array $argument ): array;
Resolves an expression in a single call argument #### `getCaseExpression()` { #mvcmodelquery-getcaseexpression }
final protected function getCaseExpression( array $expr ): array;
Resolves an expression in a single call argument #### `getExpression()` { #mvcmodelquery-getexpression }
final protected function getExpression(
    array $expr,
    bool $quoting = true
): array;
Resolves an expression from its intermediate code into an array #### `getFunctionCall()` { #mvcmodelquery-getfunctioncall }
final protected function getFunctionCall( array $expr ): array;
Resolves an expression in a single call argument #### `getGroupClause()` { #mvcmodelquery-getgroupclause }
final protected function getGroupClause( array $group ): array;
Returns a processed group clause for a SELECT statement #### `getJoin()` { #mvcmodelquery-getjoin }
final protected function getJoin(
    ManagerInterface $manager,
    array $join
): array;
Resolves a JOIN clause checking if the associated models exist #### `getJoinType()` { #mvcmodelquery-getjointype }
final protected function getJoinType( array $join ): string;
Resolves a JOIN type #### `getJoins()` { #mvcmodelquery-getjoins }
final protected function getJoins( array $select ): array;
Processes the JOINs in the query returning an internal representation for the database dialect #### `getLimitClause()` { #mvcmodelquery-getlimitclause }
final protected function getLimitClause( array $limitClause ): array;
Returns a processed limit clause for a SELECT statement #### `getMultiJoin()` { #mvcmodelquery-getmultijoin }
final protected function getMultiJoin(
    string $joinType,
    mixed $joinSource,
    string $modelAlias,
    string $joinAlias,
    RelationInterface $relation
): array;
Resolves joins involving many-to-many relations #### `getOrderClause()` { #mvcmodelquery-getorderclause }
final protected function getOrderClause( mixed $order ): array;
Returns a processed order clause for a SELECT statement #### `getQualified()` { #mvcmodelquery-getqualified }
final protected function getQualified( array $expr ): array;
Replaces the model's name to its source name in a qualified-name expression #### `getReadConnection()` { #mvcmodelquery-getreadconnection }
protected function getReadConnection(
    ModelInterface $model,
    array $intermediate = null,
    array $bindParams = [],
    array $bindTypes = []
): AdapterInterface;
Gets the read connection from the model if there is no transaction set inside the query object #### `getRelatedRecords()` { #mvcmodelquery-getrelatedrecords }
final protected function getRelatedRecords(
    ModelInterface $model,
    array $intermediate,
    array $bindParams,
    array $bindTypes
): ResultsetInterface;
Query the records on which the UPDATE/DELETE operation will be done #### `getSelectColumn()` { #mvcmodelquery-getselectcolumn }
final protected function getSelectColumn( array $column ): array;
Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex #### `getSingleJoin()` { #mvcmodelquery-getsinglejoin }
final protected function getSingleJoin(
    string $joinType,
    mixed $joinSource,
    string $modelAlias,
    string $joinAlias,
    RelationInterface $relation
): array;
Resolves joins involving has-one/belongs-to/has-many relations #### `getTable()` { #mvcmodelquery-gettable }
final protected function getTable(
    ManagerInterface $manager,
    array $qualifiedName
);
Resolves a table in a SELECT statement checking if the model exists #### `getWriteConnection()` { #mvcmodelquery-getwriteconnection }
protected function getWriteConnection(
    ModelInterface $model,
    array $intermediate = null,
    array $bindParams = [],
    array $bindTypes = []
): AdapterInterface;
Gets the write connection from the model if there is no transaction inside the query object #### `prepareDelete()` { #mvcmodelquery-preparedelete }
final protected function prepareDelete(): array;
Analyzes a DELETE intermediate code and produces an array to be executed later #### `prepareInsert()` { #mvcmodelquery-prepareinsert }
final protected function prepareInsert(): array;
Analyzes an INSERT intermediate code and produces an array to be executed later #### `prepareSelect()` { #mvcmodelquery-prepareselect }
final protected function prepareSelect(
    mixed $ast = null,
    bool $merge = false
): array;
Analyzes a SELECT intermediate code and produces an array to be executed later #### `prepareUpdate()` { #mvcmodelquery-prepareupdate }
final protected function prepareUpdate(): array;
Analyzes an UPDATE intermediate code and produces an array to be executed later #### `refreshSchemasInIntermediate()` { #mvcmodelquery-refreshschemasinintermediate }
final protected function refreshSchemasInIntermediate( array $irPhql ): array;
Refreshes the schema/source of every model referenced in a cached intermediate representation. The PHQL cache is keyed by the PHQL string only, so a model that switches its schema or source at runtime (for instance via setSchema()/setSource() in initialize()) would otherwise see the value frozen at first parse. See #17020. ## Mvc\Model\QueryInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/QueryInterface.zep){ .src-btn } Phalcon\Mvc\Model\QueryInterface Interface for Phalcon\Mvc\Model\Query
- **`Phalcon\Mvc\Model\QueryInterface`**
__Uses__ `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Methods
Public · 13
#### `cache()` { #mvcmodelqueryinterface-cache }
public function cache( array $cacheOptions ): QueryInterface;
Sets the cache parameters of the query #### `execute()` { #mvcmodelqueryinterface-execute }
public function execute(
    array $bindParams = [],
    array $bindTypes = []
);
Executes a parsed PHQL statement #### `getBindParams()` { #mvcmodelqueryinterface-getbindparams }
public function getBindParams(): array;
Returns default bind params #### `getBindTypes()` { #mvcmodelqueryinterface-getbindtypes }
public function getBindTypes(): array;
Returns default bind types #### `getCacheOptions()` { #mvcmodelqueryinterface-getcacheoptions }
public function getCacheOptions(): array;
Returns the current cache options #### `getSingleResult()` { #mvcmodelqueryinterface-getsingleresult }
public function getSingleResult(
    array $bindParams = [],
    array $bindTypes = []
): ModelInterface;
Executes the query returning the first result #### `getSql()` { #mvcmodelqueryinterface-getsql }
public function getSql(): array;
Returns the SQL to be generated by the internal PHQL (only works in SELECT statements) #### `getUniqueRow()` { #mvcmodelqueryinterface-getuniquerow }
public function getUniqueRow(): bool;
Check if the query is programmed to get only the first row in the resultset #### `parse()` { #mvcmodelqueryinterface-parse }
public function parse(): array;
Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query #### `setBindParams()` { #mvcmodelqueryinterface-setbindparams }
public function setBindParams(
    array $bindParams,
    bool $merge = false
): QueryInterface;
Set default bind parameters #### `setBindTypes()` { #mvcmodelqueryinterface-setbindtypes }
public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): QueryInterface;
Set default bind parameters #### `setSharedLock()` { #mvcmodelqueryinterface-setsharedlock }
public function setSharedLock( bool $sharedLock = false ): QueryInterface;
Set SHARED LOCK clause #### `setUniqueRow()` { #mvcmodelqueryinterface-setuniquerow }
public function setUniqueRow( bool $uniqueRow ): QueryInterface;
Tells to the query if only the first row in the resultset must be returned ## Mvc\Model\Query\Builder Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Builder.zep){ .src-btn } Helps to create PHQL queries using an OO interface
$params = [
    "models"     => [
        Users::class,
    ],
    "columns"    => ["id", "name", "status"],
    "conditions" => [
        [
            "created > :min: AND created < :max:",
            [
                "min" => "2013-01-01",
                "max" => "2014-01-01",
            ],
            [
                "min" => PDO::PARAM_STR,
                "max" => PDO::PARAM_STR,
            ],
        ],
    ],
    // or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'",
    "group"      => ["id", "name"],
    "having"     => "name = 'Kamil'",
    "order"      => ["name", "id"],
    "limit"      => 20,
    "offset"     => 20,
    // or "limit" => [20, 20],
];

$queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params);
- **`Phalcon\Mvc\Model\Query\Builder`** — implements [`Phalcon\Mvc\Model\Query\BuilderInterface`](#mvcmodelquerybuilderinterface), [`Phalcon\Di\InjectionAwareInterface`](phalcon_di.md#diinjectionawareinterface)
__Uses__ `Phalcon\Db\Column` · `Phalcon\Di\Di` · `Phalcon\Di\DiInterface` · `Phalcon\Di\InjectionAwareInterface` · `Phalcon\Mvc\Model\Exception` · `Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable` · `Phalcon\Mvc\Model\QueryInterface` · `Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap` · `Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid` · `Phalcon\Mvc\Model\Query\Exceptions\Builder\ModelRequired` · `Phalcon\Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey` · `Phalcon\Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable` · `Phalcon\Support\Settings` { .api-uses } ### Method Summary
public __construct(mixed $params = null,DiInterface $container = null) Phalcon\Mvc\Model\Query\Builder constructor public BuilderInterface addFrom(string $model,string $alias = null) Add a model to take part of the query public BuilderInterface andHaving(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current HAVING conditions clause using a AND operator public BuilderInterface andWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current WHERE conditions using a AND operator public string autoescape( string $identifier ) Automatically escapes identifiers but only if they need to be escaped. public BuilderInterface betweenHaving(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a BETWEEN condition to the current HAVING conditions clause public BuilderInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a BETWEEN condition to the current WHERE conditions public BuilderInterface columns( mixed $columns ) Sets the columns to be queried. The columns can be either a string or public BuilderInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public BuilderInterface forUpdate( bool $forUpdate ) Sets a FOR UPDATE clause public BuilderInterface from( mixed $models ) Sets the models who makes part of the query public array getBindParams() Returns default bind params public array getBindTypes() Returns default bind types public getColumns() Return the columns to be queried public DiInterface getDI() Returns the DependencyInjector container public bool getDistinct() Returns SELECT DISTINCT / SELECT ALL flag public getFrom() Return the models who makes part of the query public array getGroupBy() Returns the GROUP BY clause public string|null getHaving() Return the current having clause public array getJoins() Return join parts of the query public getLimit() Returns the current LIMIT clause public string|array|null getModels() Returns the models involved in the query public int getOffset() Returns the current OFFSET clause public getOrderBy() Returns the set ORDER BY clause public string getPhql() Returns a PHQL statement built based on the builder parameters public QueryInterface getQuery() Returns the query built public getWhere() Return the conditions for the query public BuilderInterface groupBy( mixed $group ) Sets a GROUP BY clause public BuilderInterface having(string $conditions,array $bindParams = [],array $bindTypes = []) Sets the HAVING condition clause public BuilderInterface inHaving(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends an IN condition to the current HAVING conditions clause public BuilderInterface inWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends an IN condition to the current WHERE conditions public BuilderInterface innerJoin(string $model,string $conditions = null,string $alias = null) Adds an INNER join to the query public BuilderInterface join(string $model,string $conditions = null,string $alias = null,string $type = null) Adds an :type: join (by default type - INNER) to the query public BuilderInterface leftJoin(string $model,string $conditions = null,string $alias = null) Adds a LEFT join to the query public BuilderInterface limit(int $limit,mixed $offset = null) Sets a LIMIT clause, optionally an offset clause public BuilderInterface notBetweenHaving(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT BETWEEN condition to the current HAVING conditions clause public BuilderInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT BETWEEN condition to the current WHERE conditions public BuilderInterface notInHaving(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT IN condition to the current HAVING conditions clause public BuilderInterface notInWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT IN condition to the current WHERE conditions public BuilderInterface offset( int $offset ) Sets an OFFSET clause public BuilderInterface orHaving(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current HAVING conditions clause using an OR operator public BuilderInterface orWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current conditions using an OR operator public BuilderInterface orderBy( mixed $orderBy ) Sets an ORDER BY condition clause public BuilderInterface rightJoin(string $model,string $conditions = null,string $alias = null) Adds a RIGHT join to the query public BuilderInterface setBindParams(array $bindParams,bool $merge = false) Set default bind parameters public BuilderInterface setBindTypes(array $bindTypes,bool $merge = false) Set default bind types public void setDI( DiInterface $container ) Sets the DependencyInjector container public BuilderInterface where(string $conditions,array $bindParams = [],array $bindTypes = []) Sets the query WHERE conditions protected BuilderInterface conditionBetween(string $clause,string $operator,string $expr,mixed $minimum,mixed $maximum) Appends a BETWEEN condition protected BuilderInterface conditionIn(string $clause,string $operator,string $expr,array $values) Appends an IN condition protected BuilderInterface conditionNotBetween(string $clause,string $operator,string $expr,mixed $minimum,mixed $maximum) Appends a NOT BETWEEN condition protected BuilderInterface conditionNotIn(string $clause,string $operator,string $expr,array $values) Appends a NOT IN condition
### Properties
protected array $bindParams = []
protected array $bindTypes = []
protected array|string|null $columns = null
protected array|string|null $conditions = null
protected DiInterface|null $container
protected mixed $distinct = null
protected bool $forUpdate = false
protected array $group = []
protected string|null $having = null
protected int $hiddenParamNumber = 0
protected array $joins = []
protected array|string $limit
protected array|string $models
protected int $offset = 0
protected array|string $order
protected bool $sharedLock = false
### Methods
Public · 48
#### `__construct()` { #mvcmodelquerybuilder-__construct }
public function __construct(
    mixed $params = null,
    DiInterface $container = null
);
Phalcon\Mvc\Model\Query\Builder constructor #### `addFrom()` { #mvcmodelquerybuilder-addfrom }
public function addFrom(
    string $model,
    string $alias = null
): BuilderInterface;
Add a model to take part of the query
// Load data from models Robots
$builder->addFrom(
    Robots::class
);

// Load data from model 'Robots' using 'r' as alias in PHQL
$builder->addFrom(
    Robots::class,
    "r"
);
#### `andHaving()` { #mvcmodelquerybuilder-andhaving }
public function andHaving(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Appends a condition to the current HAVING conditions clause using a AND operator
$builder->andHaving("SUM(Robots.price) > 0");

$builder->andHaving(
    "SUM(Robots.price) > :sum:",
    [
        "sum" => 100,
    ]
);
#### `andWhere()` { #mvcmodelquerybuilder-andwhere }
public function andWhere(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Appends a condition to the current WHERE conditions using a AND operator
$builder->andWhere("name = 'Peter'");

$builder->andWhere(
    "name = :name: AND id > :id:",
    [
        "name" => "Peter",
        "id"   => 100,
    ]
);
#### `autoescape()` { #mvcmodelquerybuilder-autoescape }
final public function autoescape( string $identifier ): string;
Automatically escapes identifiers but only if they need to be escaped. #### `betweenHaving()` { #mvcmodelquerybuilder-betweenhaving }
public function betweenHaving(
    string $expr,
    mixed $minimum,
    mixed $maximum,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a BETWEEN condition to the current HAVING conditions clause
$builder->betweenHaving("SUM(Robots.price)", 100.25, 200.50);
#### `betweenWhere()` { #mvcmodelquerybuilder-betweenwhere }
public function betweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a BETWEEN condition to the current WHERE conditions
$builder->betweenWhere("price", 100.25, 200.50);
#### `columns()` { #mvcmodelquerybuilder-columns }
public function columns( mixed $columns ): BuilderInterface;
Sets the columns to be queried. The columns can be either a `string` or an `array` of strings. If the argument is a (single, non-embedded) string, its content can specify one or more columns, separated by commas, the same way that one uses the SQL select statement. You can use aliases, aggregate functions, etc. If you need to reference other models you will need to reference them with their namespaces. When using an array as a parameter, you will need to specify one field per array element. If a non-numeric key is defined in the array, it will be used as the alias in the query
<?php

// String, comma separated values
$builder->columns("id, category");

// Array, one column per element
$builder->columns(
    [
        "inv_id",
        "inv_total",
    ]
);

// Array with named key. The name of the key acts as an
// alias (`AS` clause)
$builder->columns(
    [
        "inv_cst_id",
        "total_invoices" => "COUNT(*)",
    ]
);

// Different models
$builder->columns(
    [
        "\Phalcon\Models\Invoices.*",
        "\Phalcon\Models\Customers.cst_name_first",
        "\Phalcon\Models\Customers.cst_name_last",
    ]
);
#### `distinct()` { #mvcmodelquerybuilder-distinct }
public function distinct( mixed $distinct ): BuilderInterface;
Sets SELECT DISTINCT / SELECT ALL flag
$builder->distinct("status");
$builder->distinct(null);
#### `forUpdate()` { #mvcmodelquerybuilder-forupdate }
public function forUpdate( bool $forUpdate ): BuilderInterface;
Sets a FOR UPDATE clause
$builder->forUpdate(true);
#### `from()` { #mvcmodelquerybuilder-from }
public function from( mixed $models ): BuilderInterface;
Sets the models who makes part of the query
$builder->from(
    Robots::class
);

$builder->from(
    [
        Robots::class,
        RobotsParts::class,
    ]
);

$builder->from(
    [
        "r"  => Robots::class,
        "rp" => RobotsParts::class,
    ]
);
#### `getBindParams()` { #mvcmodelquerybuilder-getbindparams }
public function getBindParams(): array;
Returns default bind params #### `getBindTypes()` { #mvcmodelquerybuilder-getbindtypes }
public function getBindTypes(): array;
Returns default bind types #### `getColumns()` { #mvcmodelquerybuilder-getcolumns }
public function getColumns();
Return the columns to be queried #### `getDI()` { #mvcmodelquerybuilder-getdi }
public function getDI(): DiInterface;
Returns the DependencyInjector container #### `getDistinct()` { #mvcmodelquerybuilder-getdistinct }
public function getDistinct(): bool;
Returns SELECT DISTINCT / SELECT ALL flag #### `getFrom()` { #mvcmodelquerybuilder-getfrom }
public function getFrom();
Return the models who makes part of the query #### `getGroupBy()` { #mvcmodelquerybuilder-getgroupby }
public function getGroupBy(): array;
Returns the GROUP BY clause #### `getHaving()` { #mvcmodelquerybuilder-gethaving }
public function getHaving(): string|null;
Return the current having clause #### `getJoins()` { #mvcmodelquerybuilder-getjoins }
public function getJoins(): array;
Return join parts of the query #### `getLimit()` { #mvcmodelquerybuilder-getlimit }
public function getLimit();
Returns the current LIMIT clause #### `getModels()` { #mvcmodelquerybuilder-getmodels }
public function getModels(): string|array|null;
Returns the models involved in the query #### `getOffset()` { #mvcmodelquerybuilder-getoffset }
public function getOffset(): int;
Returns the current OFFSET clause #### `getOrderBy()` { #mvcmodelquerybuilder-getorderby }
public function getOrderBy();
Returns the set ORDER BY clause #### `getPhql()` { #mvcmodelquerybuilder-getphql }
final public function getPhql(): string;
Returns a PHQL statement built based on the builder parameters #### `getQuery()` { #mvcmodelquerybuilder-getquery }
public function getQuery(): QueryInterface;
Returns the query built #### `getWhere()` { #mvcmodelquerybuilder-getwhere }
public function getWhere();
Return the conditions for the query #### `groupBy()` { #mvcmodelquerybuilder-groupby }
public function groupBy( mixed $group ): BuilderInterface;
Sets a GROUP BY clause
$builder->groupBy(
    [
        "Robots.name",
    ]
);
#### `having()` { #mvcmodelquerybuilder-having }
public function having(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Sets the HAVING condition clause
$builder->having("SUM(Robots.price) > 0");

$builder->having(
    "SUM(Robots.price) > :sum:",
    [
        "sum" => 100,
    ]
);
#### `inHaving()` { #mvcmodelquerybuilder-inhaving }
public function inHaving(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends an IN condition to the current HAVING conditions clause
$builder->inHaving("SUM(Robots.price)", [100, 200]);
#### `inWhere()` { #mvcmodelquerybuilder-inwhere }
public function inWhere(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends an IN condition to the current WHERE conditions
$builder->inWhere(
    "id",
    [1, 2, 3]
);
#### `innerJoin()` { #mvcmodelquerybuilder-innerjoin }
public function innerJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;
Adds an INNER join to the query
// Inner Join model 'Robots' with automatic conditions and alias
$builder->innerJoin(
    Robots::class
);

// Inner Join model 'Robots' specifying conditions
$builder->innerJoin(
    Robots::class,
    "Robots.id = RobotsParts.robots_id"
);

// Inner Join model 'Robots' specifying conditions and alias
$builder->innerJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);
#### `join()` { #mvcmodelquerybuilder-join }
public function join(
    string $model,
    string $conditions = null,
    string $alias = null,
    string $type = null
): BuilderInterface;
Adds an :type: join (by default type - INNER) to the query
// Inner Join model 'Robots' with automatic conditions and alias
$builder->join(
    Robots::class
);

// Inner Join model 'Robots' specifying conditions
$builder->join(
    Robots::class,
    "Robots.id = RobotsParts.robots_id"
);

// Inner Join model 'Robots' specifying conditions and alias
$builder->join(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);

// Left Join model 'Robots' specifying conditions, alias and type of join
$builder->join(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r",
    "LEFT"
);
#### `leftJoin()` { #mvcmodelquerybuilder-leftjoin }
public function leftJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;
Adds a LEFT join to the query
$builder->leftJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);
#### `limit()` { #mvcmodelquerybuilder-limit }
public function limit(
    int $limit,
    mixed $offset = null
): BuilderInterface;
Sets a LIMIT clause, optionally an offset clause
$builder->limit(100);
$builder->limit(100, 20);
$builder->limit("100", "20");
#### `notBetweenHaving()` { #mvcmodelquerybuilder-notbetweenhaving }
public function notBetweenHaving(
    string $expr,
    mixed $minimum,
    mixed $maximum,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT BETWEEN condition to the current HAVING conditions clause
$builder->notBetweenHaving("SUM(Robots.price)", 100.25, 200.50);
#### `notBetweenWhere()` { #mvcmodelquerybuilder-notbetweenwhere }
public function notBetweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT BETWEEN condition to the current WHERE conditions
$builder->notBetweenWhere("price", 100.25, 200.50);
#### `notInHaving()` { #mvcmodelquerybuilder-notinhaving }
public function notInHaving(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT IN condition to the current HAVING conditions clause
$builder->notInHaving("SUM(Robots.price)", [100, 200]);
#### `notInWhere()` { #mvcmodelquerybuilder-notinwhere }
public function notInWhere(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT IN condition to the current WHERE conditions
$builder->notInWhere("id", [1, 2, 3]);
#### `offset()` { #mvcmodelquerybuilder-offset }
public function offset( int $offset ): BuilderInterface;
Sets an OFFSET clause
$builder->offset(30);
#### `orHaving()` { #mvcmodelquerybuilder-orhaving }
public function orHaving(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Appends a condition to the current HAVING conditions clause using an OR operator
$builder->orHaving("SUM(Robots.price) > 0");

$builder->orHaving(
    "SUM(Robots.price) > :sum:",
    [
        "sum" => 100,
    ]
);
#### `orWhere()` { #mvcmodelquerybuilder-orwhere }
public function orWhere(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Appends a condition to the current conditions using an OR operator
$builder->orWhere("name = 'Peter'");

$builder->orWhere(
    "name = :name: AND id > :id:",
    [
        "name" => "Peter",
        "id"   => 100,
    ]
);
#### `orderBy()` { #mvcmodelquerybuilder-orderby }
public function orderBy( mixed $orderBy ): BuilderInterface;
Sets an ORDER BY condition clause
$builder->orderBy("Robots.name");
$builder->orderBy(["1", "Robots.name"]);
$builder->orderBy(["Robots.name DESC"]);
#### `rightJoin()` { #mvcmodelquerybuilder-rightjoin }
public function rightJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;
Adds a RIGHT join to the query
$builder->rightJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);
#### `setBindParams()` { #mvcmodelquerybuilder-setbindparams }
public function setBindParams(
    array $bindParams,
    bool $merge = false
): BuilderInterface;
Set default bind parameters #### `setBindTypes()` { #mvcmodelquerybuilder-setbindtypes }
public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): BuilderInterface;
Set default bind types #### `setDI()` { #mvcmodelquerybuilder-setdi }
public function setDI( DiInterface $container ): void;
Sets the DependencyInjector container #### `where()` { #mvcmodelquerybuilder-where }
public function where(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Sets the query WHERE conditions
$builder->where(100);

$builder->where("name = 'Peter'");

$builder->where(
    "name = :name: AND id > :id:",
    [
        "name" => "Peter",
        "id"   => 100,
    ]
);
Protected · 4
#### `conditionBetween()` { #mvcmodelquerybuilder-conditionbetween }
protected function conditionBetween(
    string $clause,
    string $operator,
    string $expr,
    mixed $minimum,
    mixed $maximum
): BuilderInterface;
Appends a BETWEEN condition #### `conditionIn()` { #mvcmodelquerybuilder-conditionin }
protected function conditionIn(
    string $clause,
    string $operator,
    string $expr,
    array $values
): BuilderInterface;
Appends an IN condition #### `conditionNotBetween()` { #mvcmodelquerybuilder-conditionnotbetween }
protected function conditionNotBetween(
    string $clause,
    string $operator,
    string $expr,
    mixed $minimum,
    mixed $maximum
): BuilderInterface;
Appends a NOT BETWEEN condition #### `conditionNotIn()` { #mvcmodelquerybuilder-conditionnotin }
protected function conditionNotIn(
    string $clause,
    string $operator,
    string $expr,
    array $values
): BuilderInterface;
Appends a NOT IN condition ## Mvc\Model\Query\BuilderInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/BuilderInterface.zep){ .src-btn } Interface for Phalcon\Mvc\Model\Query\Builder
- **`Phalcon\Mvc\Model\Query\BuilderInterface`**
__Uses__ `Phalcon\Mvc\Model\QueryInterface` { .api-uses } ### Method Summary
public BuilderInterface addFrom(string $model,string $alias = null) Add a model to take part of the query public BuilderInterface andWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current conditions using a AND operator public BuilderInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a BETWEEN condition to the current conditions public BuilderInterface columns( mixed $columns ) Sets the columns to be queried. The columns can be either a string or public BuilderInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public BuilderInterface forUpdate( bool $forUpdate ) Sets a FOR UPDATE clause public BuilderInterface from( mixed $models ) Sets the models who makes part of the query public array getBindParams() Returns default bind params public array getBindTypes() Returns default bind types public getColumns() Return the columns to be queried public bool getDistinct() Returns SELECT DISTINCT / SELECT ALL flag public getFrom() Return the models who makes part of the query public array getGroupBy() Returns the GROUP BY clause public string|null getHaving() Returns the HAVING condition clause public array getJoins() Return join parts of the query public getLimit() Returns the current LIMIT clause public string|array|null getModels() Returns the models involved in the query public int getOffset() Returns the current OFFSET clause public getOrderBy() Return the set ORDER BY clause public string getPhql() Returns a PHQL statement built based on the builder parameters public QueryInterface getQuery() Returns the query built public getWhere() Return the conditions for the query public BuilderInterface groupBy( mixed $group ) Sets a GROUP BY clause public BuilderInterface having(string $conditions,array $bindParams = [],array $bindTypes = []) Sets a HAVING condition clause public BuilderInterface inWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends an IN condition to the current conditions public BuilderInterface innerJoin(string $model,string $conditions = null,string $alias = null) Adds an INNER join to the query public BuilderInterface join(string $model,string $conditions = null,string $alias = null) Adds an :type: join (by default type - INNER) to the query public BuilderInterface leftJoin(string $model,string $conditions = null,string $alias = null) Adds a LEFT join to the query public BuilderInterface limit(int $limit,mixed $offset = null) Sets a LIMIT clause public BuilderInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT BETWEEN condition to the current conditions public BuilderInterface notInWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT IN condition to the current conditions public BuilderInterface offset( int $offset ) Sets an OFFSET clause public BuilderInterface orWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current conditions using an OR operator public BuilderInterface orderBy( mixed $orderBy ) Sets an ORDER BY condition clause public BuilderInterface rightJoin(string $model,string $conditions = null,string $alias = null) Adds a RIGHT join to the query public BuilderInterface setBindParams(array $bindParams,bool $merge = false) Set default bind parameters public BuilderInterface setBindTypes(array $bindTypes,bool $merge = false) Set default bind types public BuilderInterface where(string $conditions,array $bindParams = [],array $bindTypes = []) Sets conditions for the query
### Constants
string OPERATOR_AND = "and"
string OPERATOR_OR = "or"
### Methods
Public · 38
#### `addFrom()` { #mvcmodelquerybuilderinterface-addfrom }
public function addFrom(
    string $model,
    string $alias = null
): BuilderInterface;
Add a model to take part of the query #### `andWhere()` { #mvcmodelquerybuilderinterface-andwhere }
public function andWhere(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Appends a condition to the current conditions using a AND operator #### `betweenWhere()` { #mvcmodelquerybuilderinterface-betweenwhere }
public function betweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a BETWEEN condition to the current conditions #### `columns()` { #mvcmodelquerybuilderinterface-columns }
public function columns( mixed $columns ): BuilderInterface;
Sets the columns to be queried. The columns can be either a `string` or an `array` of strings. If the argument is a (single, non-embedded) string, its content can specify one or more columns, separated by commas, the same way that one uses the SQL select statement. You can use aliases, aggregate functions, etc. If you need to reference other models you will need to reference them with their namespaces. When using an array as a parameter, you will need to specify one field per array element. If a non-numeric key is defined in the array, it will be used as the alias in the query
<?php

// String, comma separated values
$builder->columns("id, name");

// Array, one column per element
$builder->columns(
    [
        "id",
        "name",
    ]
);

// Array, named keys. The name of the key acts as an alias (`AS` clause)
$builder->columns(
    [
        "name",
        "number" => "COUNT(*)",
    ]
);

// Different models
$builder->columns(
    [
        "\Phalcon\Models\Invoices.*",
        "\Phalcon\Models\Customers.cst_name_first",
        "\Phalcon\Models\Customers.cst_name_last",
    ]
);
#### `distinct()` { #mvcmodelquerybuilderinterface-distinct }
public function distinct( mixed $distinct ): BuilderInterface;
Sets SELECT DISTINCT / SELECT ALL flag
$builder->distinct("status");
$builder->distinct(null);
#### `forUpdate()` { #mvcmodelquerybuilderinterface-forupdate }
public function forUpdate( bool $forUpdate ): BuilderInterface;
Sets a FOR UPDATE clause
$builder->forUpdate(true);
#### `from()` { #mvcmodelquerybuilderinterface-from }
public function from( mixed $models ): BuilderInterface;
Sets the models who makes part of the query #### `getBindParams()` { #mvcmodelquerybuilderinterface-getbindparams }
public function getBindParams(): array;
Returns default bind params #### `getBindTypes()` { #mvcmodelquerybuilderinterface-getbindtypes }
public function getBindTypes(): array;
Returns default bind types #### `getColumns()` { #mvcmodelquerybuilderinterface-getcolumns }
public function getColumns();
Return the columns to be queried #### `getDistinct()` { #mvcmodelquerybuilderinterface-getdistinct }
public function getDistinct(): bool;
Returns SELECT DISTINCT / SELECT ALL flag #### `getFrom()` { #mvcmodelquerybuilderinterface-getfrom }
public function getFrom();
Return the models who makes part of the query #### `getGroupBy()` { #mvcmodelquerybuilderinterface-getgroupby }
public function getGroupBy(): array;
Returns the GROUP BY clause #### `getHaving()` { #mvcmodelquerybuilderinterface-gethaving }
public function getHaving(): string|null;
Returns the HAVING condition clause #### `getJoins()` { #mvcmodelquerybuilderinterface-getjoins }
public function getJoins(): array;
Return join parts of the query #### `getLimit()` { #mvcmodelquerybuilderinterface-getlimit }
public function getLimit();
Returns the current LIMIT clause #### `getModels()` { #mvcmodelquerybuilderinterface-getmodels }
public function getModels(): string|array|null;
Returns the models involved in the query #### `getOffset()` { #mvcmodelquerybuilderinterface-getoffset }
public function getOffset(): int;
Returns the current OFFSET clause #### `getOrderBy()` { #mvcmodelquerybuilderinterface-getorderby }
public function getOrderBy();
Return the set ORDER BY clause #### `getPhql()` { #mvcmodelquerybuilderinterface-getphql }
public function getPhql(): string;
Returns a PHQL statement built based on the builder parameters #### `getQuery()` { #mvcmodelquerybuilderinterface-getquery }
public function getQuery(): QueryInterface;
Returns the query built #### `getWhere()` { #mvcmodelquerybuilderinterface-getwhere }
public function getWhere();
Return the conditions for the query #### `groupBy()` { #mvcmodelquerybuilderinterface-groupby }
public function groupBy( mixed $group ): BuilderInterface;
Sets a GROUP BY clause #### `having()` { #mvcmodelquerybuilderinterface-having }
public function having(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Sets a HAVING condition clause #### `inWhere()` { #mvcmodelquerybuilderinterface-inwhere }
public function inWhere(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends an IN condition to the current conditions #### `innerJoin()` { #mvcmodelquerybuilderinterface-innerjoin }
public function innerJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;
Adds an INNER join to the query #### `join()` { #mvcmodelquerybuilderinterface-join }
public function join(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;
Adds an :type: join (by default type - INNER) to the query #### `leftJoin()` { #mvcmodelquerybuilderinterface-leftjoin }
public function leftJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;
Adds a LEFT join to the query #### `limit()` { #mvcmodelquerybuilderinterface-limit }
public function limit(
    int $limit,
    mixed $offset = null
): BuilderInterface;
Sets a LIMIT clause #### `notBetweenWhere()` { #mvcmodelquerybuilderinterface-notbetweenwhere }
public function notBetweenWhere(
    string $expr,
    mixed $minimum,
    mixed $maximum,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT BETWEEN condition to the current conditions #### `notInWhere()` { #mvcmodelquerybuilderinterface-notinwhere }
public function notInWhere(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT IN condition to the current conditions #### `offset()` { #mvcmodelquerybuilderinterface-offset }
public function offset( int $offset ): BuilderInterface;
Sets an OFFSET clause #### `orWhere()` { #mvcmodelquerybuilderinterface-orwhere }
public function orWhere(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Appends a condition to the current conditions using an OR operator #### `orderBy()` { #mvcmodelquerybuilderinterface-orderby }
public function orderBy( mixed $orderBy ): BuilderInterface;
Sets an ORDER BY condition clause #### `rightJoin()` { #mvcmodelquerybuilderinterface-rightjoin }
public function rightJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;
Adds a RIGHT join to the query #### `setBindParams()` { #mvcmodelquerybuilderinterface-setbindparams }
public function setBindParams(
    array $bindParams,
    bool $merge = false
): BuilderInterface;
Set default bind parameters #### `setBindTypes()` { #mvcmodelquerybuilderinterface-setbindtypes }
public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): BuilderInterface;
Set default bind types #### `where()` { #mvcmodelquerybuilderinterface-where }
public function where(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;
Sets conditions for the query ## Mvc\Model\Query\Exceptions\AmbiguousColumn Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/AmbiguousColumn.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\AmbiguousColumn`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsambiguouscolumn-__construct }
public function __construct(
    string $name,
    string $phql
);
## Mvc\Model\Query\Exceptions\AmbiguousJoinRelation Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/AmbiguousJoinRelation.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\AmbiguousJoinRelation`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsambiguousjoinrelation-__construct }
public function __construct(
    string $from,
    string $join,
    string $phql
);
## Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/BindParameterNotInPlaceholders.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbindparameternotinplaceholders-__construct }
public function __construct( string $wildcard );
## Mvc\Model\Query\Exceptions\BindTypeRequiresArray Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/BindTypeRequiresArray.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\BindTypeRequiresArray`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbindtyperequiresarray-__construct }
public function __construct( string $name );
## Mvc\Model\Query\Exceptions\BindValueRequired Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/BindValueRequired.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\BindValueRequired`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbindvaluerequired-__construct }
public function __construct( string $name );
## Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/Builder/BuilderColumnNotInMap.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbuilderbuildercolumnnotinmap-__construct }
public function __construct( string $column );
## Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/Builder/BuilderConditionInvalid.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbuilderbuilderconditioninvalid-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\Builder\ModelRequired Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/Builder/ModelRequired.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\Builder\ModelRequired`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbuildermodelrequired-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/Builder/NoPrimaryKey.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbuildernoprimarykey-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/Builder/OperatorNotAvailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsbuilderoperatornotavailable-__construct }
public function __construct( string $operator );
## Mvc\Model\Query\Exceptions\ColumnNotInDomain Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/ColumnNotInDomain.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInDomain`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionscolumnnotindomain-__construct }
public function __construct(
    string $name,
    string $model,
    string $phql
);
## Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/ColumnNotInSelectedModels.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionscolumnnotinselectedmodels-__construct }
public function __construct(
    string $name,
    string $tag,
    string $phql
);
## Mvc\Model\Query\Exceptions\CorruptedAst Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/CorruptedAst.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\CorruptedAst`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionscorruptedast-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\CorruptedDeleteAst Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/CorruptedDeleteAst.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\CorruptedDeleteAst`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionscorrupteddeleteast-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\CorruptedInsertAst Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/CorruptedInsertAst.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\CorruptedInsertAst`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionscorruptedinsertast-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\CorruptedSelectAst Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/CorruptedSelectAst.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\CorruptedSelectAst`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionscorruptedselectast-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\CorruptedUpdateAst Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/CorruptedUpdateAst.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\CorruptedUpdateAst`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionscorruptedupdateast-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/DeleteMultipleNotSupported.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsdeletemultiplenotsupported-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\DuplicateAlias Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/DuplicateAlias.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\DuplicateAlias`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsduplicatealias-__construct }
public function __construct(
    string $name,
    string $phql
);
## Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/EmptyArrayPlaceholderValue.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsemptyarrayplaceholdervalue-__construct }
public function __construct( string $name );
## Mvc\Model\Query\Exceptions\InsertColumnCountMismatch Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InsertColumnCountMismatch.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InsertColumnCountMismatch`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinsertcolumncountmismatch-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\InvalidCachedResultset Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InvalidCachedResultset.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InvalidCachedResultset`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinvalidcachedresultset-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\InvalidCachingOptions Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InvalidCachingOptions.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InvalidCachingOptions`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinvalidcachingoptions-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\InvalidColumnDefinition Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InvalidColumnDefinition.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InvalidColumnDefinition`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinvalidcolumndefinition-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\InvalidInjectedManager Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InvalidInjectedManager.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedManager`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinvalidinjectedmanager-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\InvalidInjectedMetadata Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InvalidInjectedMetadata.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedMetadata`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinvalidinjectedmetadata-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\InvalidQueryCacheService Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InvalidQueryCacheService.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InvalidQueryCacheService`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinvalidquerycacheservice-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\InvalidResultsetClass Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/InvalidResultsetClass.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\InvalidResultsetClass`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsinvalidresultsetclass-__construct }
public function __construct( string $className );
## Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/JoinAliasAlreadyUsed.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsjoinaliasalreadyused-__construct }
public function __construct(
    string $alias,
    string $phql
);
## Mvc\Model\Query\Exceptions\JoinFieldCountMismatch Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/JoinFieldCountMismatch.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\JoinFieldCountMismatch`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsjoinfieldcountmismatch-__construct }
public function __construct(
    string $model,
    string $join,
    string $phql
);
## Mvc\Model\Query\Exceptions\MissingCacheKey Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/MissingCacheKey.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\MissingCacheKey`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmissingcachekey-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\MissingMetaData Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/MissingMetaData.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\MissingMetaData`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmissingmetadata-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\MissingModelAttribute Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/MissingModelAttribute.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\MissingModelAttribute`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmissingmodelattribute-__construct }
public function __construct(
    string $model,
    string $attribute,
    string $phql
);
## Mvc\Model\Query\Exceptions\MissingModelsManager Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/MissingModelsManager.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\MissingModelsManager`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmissingmodelsmanager-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\MixedDatabaseSystems Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/MixedDatabaseSystems.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\MixedDatabaseSystems`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmixeddatabasesystems-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\ModelSourceNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/ModelSourceNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\ModelSourceNotFound`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmodelsourcenotfound-__construct }
public function __construct(
    string $name,
    string $phql
);
## Mvc\Model\Query\Exceptions\ModelsListNotLoaded Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/ModelsListNotLoaded.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\ModelsListNotLoaded`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmodelslistnotloaded-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/MultipleSqlStatementsNotSupported.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsmultiplesqlstatementsnotsupported-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\NoModelForAlias Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/NoModelForAlias.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\NoModelForAlias`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsnomodelforalias-__construct }
public function __construct(
    string $model,
    string $phql
);
## Mvc\Model\Query\Exceptions\PhqlColumnNotInMap Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/PhqlColumnNotInMap.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\PhqlColumnNotInMap`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsphqlcolumnnotinmap-__construct }
public function __construct( string $fieldName );
## Mvc\Model\Query\Exceptions\ReadConnectionMissing Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/ReadConnectionMissing.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\ReadConnectionMissing`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsreadconnectionmissing-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\RelationshipNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/RelationshipNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\RelationshipNotFound`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsrelationshipnotfound-__construct }
public function __construct(
    string $model,
    string $relationship,
    string $phql
);
## Mvc\Model\Query\Exceptions\ResultsetClassNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/ResultsetClassNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\ResultsetClassNotFound`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsresultsetclassnotfound-__construct }
public function __construct( string $className );
## Mvc\Model\Query\Exceptions\ResultsetNonCacheable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/ResultsetNonCacheable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\ResultsetNonCacheable`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsresultsetnoncacheable-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\UnknownBindType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UnknownBindType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UnknownBindType`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsunknownbindtype-__construct }
public function __construct( string $type );
## Mvc\Model\Query\Exceptions\UnknownColumnType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UnknownColumnType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UnknownColumnType`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsunknowncolumntype-__construct }
public function __construct( string $type );
## Mvc\Model\Query\Exceptions\UnknownJoinType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UnknownJoinType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UnknownJoinType`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsunknownjointype-__construct }
public function __construct(
    string $type,
    string $phql
);
## Mvc\Model\Query\Exceptions\UnknownModelOrAlias Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UnknownModelOrAlias.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UnknownModelOrAlias`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsunknownmodeloralias-__construct }
public function __construct(
    string $model,
    string $tag,
    string $phql
);
## Mvc\Model\Query\Exceptions\UnknownPhqlExpression Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UnknownPhqlExpression.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpression`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsunknownphqlexpression-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UnknownPhqlExpressionType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsunknownphqlexpressiontype-__construct }
public function __construct( string $type );
## Mvc\Model\Query\Exceptions\UnknownPhqlStatement Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UnknownPhqlStatement.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlStatement`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsunknownphqlstatement-__construct }
public function __construct( string $type );
## Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/UpdateMultipleNotSupported.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionsupdatemultiplenotsupported-__construct }
public function __construct();
## Mvc\Model\Query\Exceptions\WriteConnectionMissing Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Exceptions/WriteConnectionMissing.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Query\Exceptions\WriteConnectionMissing`**
__Uses__ `Phalcon\Mvc\Model\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcmodelqueryexceptionswriteconnectionmissing-__construct }
public function __construct();
## Mvc\Model\Query\Lang Abstract [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Lang.zep){ .src-btn } Phalcon\Mvc\Model\Query\Lang PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. It allows Phalcon to offer a unified SQL language to the developer, while internally doing all the work of translating PHQL instructions to the most optimal SQL instructions depending on the RDBMS type associated with a model. To achieve the highest performance possible, we wrote a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe.
use Phalcon\Mvc\Model\Query\Lang;

$intermediate = Lang::parsePHQL(
    "SELECT r.* FROM Robots r LIMIT 10"
);
- **`Phalcon\Mvc\Model\Query\Lang`**
### Method Summary ### Methods
Public · 1
#### `parsePHQL()` { #mvcmodelquerylang-parsephql }
public static function parsePHQL( string $phql ): array;
Parses a PHQL statement returning an intermediate representation (IR) ## Mvc\Model\Query\Status Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/Status.zep){ .src-btn } This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails
$phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";

$status = $app->modelsManager->executeQuery(
    $phql,
    [
        "id"   => 100,
        "name" => "Astroy Boy",
        "type" => "mechanical",
        "year" => 1959,
    ]
);

// Check if the update was successful
if ($status->success()) {
    echo "OK";
}
- **`Phalcon\Mvc\Model\Query\Status`** — implements [`Phalcon\Mvc\Model\Query\StatusInterface`](#mvcmodelquerystatusinterface)
__Uses__ `Phalcon\Messages\MessageInterface` · `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Properties
protected ModelInterface|null $model
protected bool $success
### Methods
Public · 4
#### `__construct()` { #mvcmodelquerystatus-__construct }
public function __construct(
    bool $success,
    ModelInterface $model = null
);
Phalcon\Mvc\Model\Query\Status #### `getMessages()` { #mvcmodelquerystatus-getmessages }
public function getMessages(): MessageInterface[];
Returns the messages produced because of a failed operation #### `getModel()` { #mvcmodelquerystatus-getmodel }
public function getModel(): ModelInterface|null;
Returns the model that executed the action #### `success()` { #mvcmodelquerystatus-success }
public function success(): bool;
Allows to check if the executed operation was successful ## Mvc\Model\Query\StatusInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Query/StatusInterface.zep){ .src-btn } Interface for Phalcon\Mvc\Model\Query\Status
- **`Phalcon\Mvc\Model\Query\StatusInterface`**
__Uses__ `Phalcon\Messages\MessageInterface` · `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Methods
Public · 3
#### `getMessages()` { #mvcmodelquerystatusinterface-getmessages }
public function getMessages(): MessageInterface[];
Returns the messages produced by an operation failed #### `getModel()` { #mvcmodelquerystatusinterface-getmodel }
public function getModel(): ModelInterface|null;
Returns the model which executed the action #### `success()` { #mvcmodelquerystatusinterface-success }
public function success(): bool;
Allows to check if the executed operation was successful ## Mvc\Model\Relation Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Relation.zep){ .src-btn } Phalcon\Mvc\Model\Relation This class represents a relationship between two models
- **`Phalcon\Mvc\Model\Relation`** — implements [`Phalcon\Mvc\Model\RelationInterface`](#mvcmodelrelationinterface)
### Method Summary ### Constants
int ACTION_CASCADE = 2
int ACTION_RESTRICT = 1
int BELONGS_TO = 0
int HAS_MANY = 2
int HAS_MANY_THROUGH = 4
int HAS_ONE = 1
int HAS_ONE_THROUGH = 3
int NO_ACTION = 0
### Properties
protected array|string $fields
protected array|string $intermediateFields
protected string|null $intermediateModel = null
protected array|string $intermediateReferencedFields
protected array $options = []
protected array|string $referencedFields
protected string $referencedModel
protected int $type
### Methods
Public · 16
#### `__construct()` { #mvcmodelrelation-__construct }
public function __construct(
    int $type,
    string $referencedModel,
    mixed $fields,
    mixed $referencedFields,
    array $options = []
);
Phalcon\Mvc\Model\Relation constructor #### `getFields()` { #mvcmodelrelation-getfields }
public function getFields();
Returns the fields #### `getForeignKey()` { #mvcmodelrelation-getforeignkey }
public function getForeignKey();
Returns the foreign key configuration #### `getIntermediateFields()` { #mvcmodelrelation-getintermediatefields }
public function getIntermediateFields();
Gets the intermediate fields for has-*-through relations #### `getIntermediateModel()` { #mvcmodelrelation-getintermediatemodel }
public function getIntermediateModel(): string;
Gets the intermediate model for has-*-through relations #### `getIntermediateReferencedFields()` { #mvcmodelrelation-getintermediatereferencedfields }
public function getIntermediateReferencedFields();
Gets the intermediate referenced fields for has-*-through relations #### `getOption()` { #mvcmodelrelation-getoption }
public function getOption( string $name );
Returns an option by the specified name If the option does not exist null is returned #### `getOptions()` { #mvcmodelrelation-getoptions }
public function getOptions(): array;
Returns the options #### `getParams()` { #mvcmodelrelation-getparams }
public function getParams();
Returns parameters that must be always used when the related records are obtained #### `getReferencedFields()` { #mvcmodelrelation-getreferencedfields }
public function getReferencedFields();
Returns the referenced fields #### `getReferencedModel()` { #mvcmodelrelation-getreferencedmodel }
public function getReferencedModel(): string;
Returns the referenced model #### `getType()` { #mvcmodelrelation-gettype }
public function getType(): int;
Returns the relation type #### `isForeignKey()` { #mvcmodelrelation-isforeignkey }
public function isForeignKey(): bool;
Check whether the relation act as a foreign key #### `isReusable()` { #mvcmodelrelation-isreusable }
public function isReusable(): bool;
Check if records returned by getting belongs-to/has-many are implicitly cached during the current request #### `isThrough()` { #mvcmodelrelation-isthrough }
public function isThrough(): bool;
Check whether the relation is a 'many-to-many' relation or not #### `setIntermediateRelation()` { #mvcmodelrelation-setintermediaterelation }
public function setIntermediateRelation(
    mixed $intermediateFields,
    string $intermediateModel,
    mixed $intermediateReferencedFields
);
Sets the intermediate model data for has-*-through relations ## Mvc\Model\RelationInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/RelationInterface.zep){ .src-btn } Phalcon\Mvc\Model\RelationInterface Interface for Phalcon\Mvc\Model\Relation
- **`Phalcon\Mvc\Model\RelationInterface`**
### Method Summary ### Methods
Public · 15
#### `getFields()` { #mvcmodelrelationinterface-getfields }
public function getFields();
Returns the fields #### `getForeignKey()` { #mvcmodelrelationinterface-getforeignkey }
public function getForeignKey();
Returns the foreign key configuration #### `getIntermediateFields()` { #mvcmodelrelationinterface-getintermediatefields }
public function getIntermediateFields();
Gets the intermediate fields for has-*-through relations #### `getIntermediateModel()` { #mvcmodelrelationinterface-getintermediatemodel }
public function getIntermediateModel(): string;
Gets the intermediate model for has-*-through relations #### `getIntermediateReferencedFields()` { #mvcmodelrelationinterface-getintermediatereferencedfields }
public function getIntermediateReferencedFields();
Gets the intermediate referenced fields for has-*-through relations #### `getOption()` { #mvcmodelrelationinterface-getoption }
public function getOption( string $name );
Returns an option by the specified name If the option does not exist null is returned #### `getOptions()` { #mvcmodelrelationinterface-getoptions }
public function getOptions(): array;
Returns the options #### `getParams()` { #mvcmodelrelationinterface-getparams }
public function getParams();
Returns parameters that must be always used when the related records are obtained #### `getReferencedFields()` { #mvcmodelrelationinterface-getreferencedfields }
public function getReferencedFields();
Returns the referenced fields #### `getReferencedModel()` { #mvcmodelrelationinterface-getreferencedmodel }
public function getReferencedModel(): string;
Returns the referenced model #### `getType()` { #mvcmodelrelationinterface-gettype }
public function getType(): int;
Returns the relations type #### `isForeignKey()` { #mvcmodelrelationinterface-isforeignkey }
public function isForeignKey(): bool;
Check whether the relation act as a foreign key #### `isReusable()` { #mvcmodelrelationinterface-isreusable }
public function isReusable(): bool;
Check if records returned by getting belongs-to/has-many are implicitly cached during the current request #### `isThrough()` { #mvcmodelrelationinterface-isthrough }
public function isThrough(): bool;
Check whether the relation is a 'many-to-many' relation or not #### `setIntermediateRelation()` { #mvcmodelrelationinterface-setintermediaterelation }
public function setIntermediateRelation(
    mixed $intermediateFields,
    string $intermediateModel,
    mixed $intermediateReferencedFields
);
Sets the intermediate model data for has-*-through relations ## Mvc\Model\ResultInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/ResultInterface.zep){ .src-btn } Phalcon\Mvc\Model\ResultInterface All single objects passed as base objects to Resultsets must implement this interface
- **`Phalcon\Mvc\Model\ResultInterface`**
__Uses__ `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `setDirtyState()` { #mvcmodelresultinterface-setdirtystate }
public function setDirtyState( int $dirtyState ): ModelInterface|bool;
Sets the object's state ## Mvc\Model\Resultset Abstract [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Resultset.zep){ .src-btn } Phalcon\Mvc\Model\Resultset This component allows to Phalcon\Mvc\Model returns large resultsets with the minimum memory consumption Resultsets can be traversed using a standard foreach or a while statement. If a resultset is serialized it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before serializing.
// Using a standard foreach
$robots = Robots::find(
    [
        "type = 'virtual'",
        "order" => "name",
    ]
);

foreach ($robots as robot) {
    echo robot->name, "\n";
}

// Using a while
$robots = Robots::find(
    [
        "type = 'virtual'",
        "order" => "name",
    ]
);

$robots->rewind();

while ($robots->valid()) {
    $robot = $robots->current();

    echo $robot->name, "\n";

    $robots->next();
}
@template TKey @template TValue @implements Iterator @implements ArrayAccess
- **`Phalcon\Mvc\Model\Resultset`** — implements [`Phalcon\Mvc\Model\ResultsetInterface`](#mvcmodelresultsetinterface), `Iterator`, `SeekableIterator`, `Countable`, `ArrayAccess`, `Serializable`, `JsonSerializable` - [`Phalcon\Mvc\Model\Resultset\Complex`](#mvcmodelresultsetcomplex) - [`Phalcon\Mvc\Model\Resultset\Simple`](#mvcmodelresultsetsimple)
__Uses__ `ArrayAccess` · `Closure` · `Countable` · `Iterator` · `JsonSerializable` · `Phalcon\Cache\CacheInterface` · `Phalcon\Db\Enum` · `Phalcon\Messages\MessageInterface` · `Phalcon\Mvc\Model` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Exceptions\CursorIsImmutable` · `Phalcon\Mvc\Model\Exceptions\IndexNotInCursor` · `Phalcon\Mvc\Model\Exceptions\InvalidResultsetCacheService` · `Phalcon\Mvc\Model\Exceptions\InvalidReturnedRecord` · `Phalcon\Storage\Serializer\SerializerInterface` · `Phalcon\Support\Settings` · `SeekableIterator` · `Serializable` { .api-uses } ### Method Summary
public __construct(mixed $result,mixed $cache = null) Phalcon\Mvc\Model\Resultset constructor public int count() Counts how many rows are in the resultset public bool delete( Closure $conditionCallback = null ) Deletes every record in the resultset public ModelInterface[] filter( callable $filter ) Filters a resultset returning only those the developer requires public CacheInterface|null getCache() Returns the associated cache for the resultset public mixed|null getFirst() Get first row in the resultset public int getHydrateMode() Returns the current hydration mode public ModelInterface|null getLast() Get last row in the resultset public MessageInterface[] getMessages() Returns the error messages produced by a batch operation public mixed getResult() public int getType() Returns the internal type of data retrieval that the resultset is using public bool isFresh() Tell if the resultset if fresh or an old one cached public array jsonSerialize() Returns serialised model objects as array for json_encode. public int|null key() Gets pointer number of active row in the resultset public void next() Moves cursor to next row in the resultset public bool offsetExists( mixed $index ) Checks whether offset exists in the resultset public mixed offsetGet( mixed $index ) Gets row in a specific position of the resultset public void offsetSet(mixed $offset,mixed $value) Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface public void offsetUnset( mixed $offset ) Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface public bool refresh() public void rewind() Rewinds resultset to its beginning public void seek( mixed $position ) Changes the internal pointer to a specific position in the resultset. public ResultsetInterface setHydrateMode( int $hydrateMode ) Sets the hydration mode in the resultset public ResultsetInterface setIsFresh( bool $isFresh ) Set if the resultset is fresh or an old one cached public bool update(mixed $data,Closure $conditionCallback = null) Updates every record in the resultset public bool valid() Check whether internal resource has rows to fetch
### Constants
int HYDRATE_ARRAYS = 1
int HYDRATE_OBJECTS = 2
int HYDRATE_RECORDS = 0
int TYPE_RESULT_FULL = 0
int TYPE_RESULT_PARTIAL = 1
### Properties
protected mixed|null $activeRow = null
protected CacheInterface|null $cache = null
protected int $count = 0
protected array $errorMessages = []
protected int $hydrateMode = 0
protected bool $isFresh = true
protected int $pointer = 0
protected ResultInterface|bool $result Phalcon\Db\ResultInterface or false for empty resultset
protected mixed|null $row = null
protected array|null $rows = null
### Methods
Public · 26
#### `__construct()` { #mvcmodelresultset-__construct }
public function __construct(
    mixed $result,
    mixed $cache = null
);
Phalcon\Mvc\Model\Resultset constructor #### `count()` { #mvcmodelresultset-count }
final public function count(): int;
Counts how many rows are in the resultset #### `delete()` { #mvcmodelresultset-delete }
public function delete( Closure $conditionCallback = null ): bool;
Deletes every record in the resultset #### `filter()` { #mvcmodelresultset-filter }
public function filter( callable $filter ): ModelInterface[];
Filters a resultset returning only those the developer requires
$filtered = $robots->filter(
    function ($robot) {
        if ($robot->id < 3) {
            return $robot;
        }
    }
);
#### `getCache()` { #mvcmodelresultset-getcache }
public function getCache(): CacheInterface|null;
Returns the associated cache for the resultset #### `getFirst()` { #mvcmodelresultset-getfirst }
public function getFirst(): mixed|null;
Get first row in the resultset
$model = new Robots();
$manager = $model->getModelsManager();

// \Robots
$manager->createQuery('SELECT * FROM Robots')
        ->execute()
        ->getFirst();

// \Phalcon\Mvc\Model\Row
$manager->createQuery('SELECT r.id FROM Robots AS r')
        ->execute()
        ->getFirst();

// NULL
$manager->createQuery('SELECT r.id FROM Robots AS r WHERE r.name = "NON-EXISTENT"')
        ->execute()
        ->getFirst();
#### `getHydrateMode()` { #mvcmodelresultset-gethydratemode }
public function getHydrateMode(): int;
Returns the current hydration mode #### `getLast()` { #mvcmodelresultset-getlast }
public function getLast(): ModelInterface|null;
Get last row in the resultset #### `getMessages()` { #mvcmodelresultset-getmessages }
public function getMessages(): MessageInterface[];
Returns the error messages produced by a batch operation #### `getResult()` { #mvcmodelresultset-getresult }
public function getResult(): mixed;
#### `getType()` { #mvcmodelresultset-gettype }
public function getType(): int;
Returns the internal type of data retrieval that the resultset is using #### `isFresh()` { #mvcmodelresultset-isfresh }
public function isFresh(): bool;
Tell if the resultset if fresh or an old one cached #### `jsonSerialize()` { #mvcmodelresultset-jsonserialize }
public function jsonSerialize(): array;
Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present
$robots = Robots::find();

echo json_encode($robots);
#### `key()` { #mvcmodelresultset-key }
public function key(): int|null;
Gets pointer number of active row in the resultset #### `next()` { #mvcmodelresultset-next }
public function next(): void;
Moves cursor to next row in the resultset #### `offsetExists()` { #mvcmodelresultset-offsetexists }
public function offsetExists( mixed $index ): bool;
Checks whether offset exists in the resultset #### `offsetGet()` { #mvcmodelresultset-offsetget }
public function offsetGet( mixed $index ): mixed;
Gets row in a specific position of the resultset #### `offsetSet()` { #mvcmodelresultset-offsetset }
public function offsetSet(
    mixed $offset,
    mixed $value
): void;
Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface #### `offsetUnset()` { #mvcmodelresultset-offsetunset }
public function offsetUnset( mixed $offset ): void;
Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface #### `refresh()` { #mvcmodelresultset-refresh }
public function refresh(): bool;
#### `rewind()` { #mvcmodelresultset-rewind }
final public function rewind(): void;
Rewinds resultset to its beginning #### `seek()` { #mvcmodelresultset-seek }
final public function seek( mixed $position ): void;
Changes the internal pointer to a specific position in the resultset. Set the new position if required, and then set this->row #### `setHydrateMode()` { #mvcmodelresultset-sethydratemode }
public function setHydrateMode( int $hydrateMode ): ResultsetInterface;
Sets the hydration mode in the resultset #### `setIsFresh()` { #mvcmodelresultset-setisfresh }
public function setIsFresh( bool $isFresh ): ResultsetInterface;
Set if the resultset is fresh or an old one cached #### `update()` { #mvcmodelresultset-update }
public function update(
    mixed $data,
    Closure $conditionCallback = null
): bool;
Updates every record in the resultset #### `valid()` { #mvcmodelresultset-valid }
public function valid(): bool;
Check whether internal resource has rows to fetch ## Mvc\Model\ResultsetInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/ResultsetInterface.zep){ .src-btn } Phalcon\Mvc\Model\ResultsetInterface Interface for Phalcon\Mvc\Model\Resultset
- **`Phalcon\Mvc\Model\ResultsetInterface`**
__Uses__ `Closure` · `Phalcon\Messages\MessageInterface` · `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Methods
Public · 13
#### `delete()` { #mvcmodelresultsetinterface-delete }
public function delete( Closure $conditionCallback = null ): bool;
Deletes every record in the resultset #### `filter()` { #mvcmodelresultsetinterface-filter }
public function filter( callable $filter ): ModelInterface[];
Filters a resultset returning only those the developer requires
$filtered = $robots->filter(
    function ($robot) {
        if ($robot->id < 3) {
            return $robot;
        }
    }
);
#### `getCache()` { #mvcmodelresultsetinterface-getcache }
public function getCache(): mixed|null;
Returns the associated cache for the resultset #### `getFirst()` { #mvcmodelresultsetinterface-getfirst }
public function getFirst(): mixed|null;
Get first row in the resultset #### `getHydrateMode()` { #mvcmodelresultsetinterface-gethydratemode }
public function getHydrateMode(): int;
Returns the current hydration mode #### `getLast()` { #mvcmodelresultsetinterface-getlast }
public function getLast(): ModelInterface|null;
Get last row in the resultset #### `getMessages()` { #mvcmodelresultsetinterface-getmessages }
public function getMessages(): MessageInterface[];
Returns the error messages produced by a batch operation #### `getType()` { #mvcmodelresultsetinterface-gettype }
public function getType(): int;
Returns the internal type of data retrieval that the resultset is using #### `isFresh()` { #mvcmodelresultsetinterface-isfresh }
public function isFresh(): bool;
Tell if the resultset if fresh or an old one cached #### `setHydrateMode()` { #mvcmodelresultsetinterface-sethydratemode }
public function setHydrateMode( int $hydrateMode ): ResultsetInterface;
Sets the hydration mode in the resultset #### `setIsFresh()` { #mvcmodelresultsetinterface-setisfresh }
public function setIsFresh( bool $isFresh ): ResultsetInterface;
Set if the resultset is fresh or an old one cached #### `toArray()` { #mvcmodelresultsetinterface-toarray }
public function toArray(): array;
Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. #### `update()` { #mvcmodelresultsetinterface-update }
public function update(
    mixed $data,
    Closure $conditionCallback = null
): bool;
Updates every record in the resultset ## Mvc\Model\Resultset\Complex Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Resultset/Complex.zep){ .src-btn } Phalcon\Mvc\Model\Resultset\Complex Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required @template TKey of int @template TValue of mixed
- [`Phalcon\Mvc\Model\Resultset`](#mvcmodelresultset) - **`Phalcon\Mvc\Model\Resultset\Complex`**
__Uses__ `Phalcon\Db\ResultInterface` · `Phalcon\Di\Di` · `Phalcon\Di\DiInterface` · `Phalcon\Mvc\Model` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Exception` · `Phalcon\Mvc\Model\Exceptions\CorruptColumnType` · `Phalcon\Mvc\Model\Exceptions\InvalidContainer` · `Phalcon\Mvc\Model\Exceptions\InvalidSerializationData` · `Phalcon\Mvc\Model\Resultset` · `Phalcon\Mvc\Model\ResultsetInterface` · `Phalcon\Mvc\Model\Row` · `Phalcon\Storage\Serializer\SerializerInterface` · `Phalcon\Support\Settings` · `stdClass` { .api-uses } ### Method Summary ### Properties
protected array $columnTypes
protected bool $disableHydration = false Unserialised result-set hydrated all rows already. unserialise() sets disableHydration to true
### Methods
Public · 7
#### `__construct()` { #mvcmodelresultsetcomplex-__construct }
public function __construct(
    mixed $columnTypes,
    ResultInterface $result = null,
    mixed $cache = null
);
Phalcon\Mvc\Model\Resultset\Complex constructor #### `__serialize()` { #mvcmodelresultsetcomplex-__serialize }
public function __serialize(): array;
#### `__unserialize()` { #mvcmodelresultsetcomplex-__unserialize }
public function __unserialize( array $data ): void;
#### `current()` { #mvcmodelresultsetcomplex-current }
final public function current(): mixed;
Returns current row in the resultset #### `serialize()` { #mvcmodelresultsetcomplex-serialize }
public function serialize(): string;
Serializing a resultset will dump all related rows into a big array, serialize it and return the resulting string #### `toArray()` { #mvcmodelresultsetcomplex-toarray }
public function toArray(): array;
Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. #### `unserialize()` { #mvcmodelresultsetcomplex-unserialize }
public function unserialize( mixed $data ): void;
Unserializing a resultset will allow to only works on the rows present in the saved state ## Mvc\Model\Resultset\Simple Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Resultset/Simple.zep){ .src-btn } Phalcon\Mvc\Model\Resultset\Simple Simple resultsets only contains a complete objects This class builds every complete object as it is required @template TKey of int @template TValue of \Phalcon\Mvc\ModelInterface
- [`Phalcon\Mvc\Model\Resultset`](#mvcmodelresultset) - **`Phalcon\Mvc\Model\Resultset\Simple`**
__Uses__ `Phalcon\Di\Di` · `Phalcon\Di\DiInterface` · `Phalcon\Mvc\Model` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Exception` · `Phalcon\Mvc\Model\Exceptions\InvalidContainer` · `Phalcon\Mvc\Model\Exceptions\InvalidSerializationData` · `Phalcon\Mvc\Model\Exceptions\ResultsetColumnNotInMap` · `Phalcon\Mvc\Model\Resultset` · `Phalcon\Mvc\Model\Row` · `Phalcon\Storage\Serializer\SerializerInterface` · `Phalcon\Support\Settings` { .api-uses } ### Method Summary ### Properties
protected array|string $columnMap
protected bool $keepSnapshots = false
protected ModelInterface|Row $model
### Methods
Public · 7
#### `__construct()` { #mvcmodelresultsetsimple-__construct }
public function __construct(
    mixed $columnMap,
    mixed $model,
    mixed $result,
    mixed $cache = null,
    bool $keepSnapshots = false
);
Phalcon\Mvc\Model\Resultset\Simple constructor #### `__serialize()` { #mvcmodelresultsetsimple-__serialize }
public function __serialize(): array;
#### `__unserialize()` { #mvcmodelresultsetsimple-__unserialize }
public function __unserialize( array $data ): void;
#### `current()` { #mvcmodelresultsetsimple-current }
final public function current(): ModelInterface|Row|null;
Returns current row in the resultset #### `serialize()` { #mvcmodelresultsetsimple-serialize }
public function serialize(): string;
Serializing a resultset will dump all related rows into a big array #### `toArray()` { #mvcmodelresultsetsimple-toarray }
public function toArray( bool $renameColumns = true ): array;
Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records #### `unserialize()` { #mvcmodelresultsetsimple-unserialize }
public function unserialize( mixed $data ): void;
Unserializing a resultset will allow to only works on the rows present in the saved state ## Mvc\Model\Row Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Row.zep){ .src-btn } This component allows Phalcon\Mvc\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x].
- `\stdClass` - **`Phalcon\Mvc\Model\Row`** — implements [`Phalcon\Mvc\EntityInterface`](#mvcentityinterface), [`Phalcon\Mvc\Model\ResultInterface`](#mvcmodelresultinterface), `ArrayAccess`, `JsonSerializable`
__Uses__ `ArrayAccess` · `JsonSerializable` · `Phalcon\Mvc\EntityInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Exceptions\IndexNotInRow` · `Phalcon\Mvc\Model\Exceptions\RowIsImmutable` { .api-uses } ### Method Summary ### Methods
Public · 9
#### `jsonSerialize()` { #mvcmodelrow-jsonserialize }
public function jsonSerialize(): array;
Serializes the object for json_encode #### `offsetExists()` { #mvcmodelrow-offsetexists }
public function offsetExists( mixed $index ): bool;
Checks whether offset exists in the row. Returns true when the property is present on the row, regardless of whether its value is null - column presence is the contract, not value truthiness. #### `offsetGet()` { #mvcmodelrow-offsetget }
public function offsetGet( mixed $index ): mixed;
Gets a record in a specific position of the row #### `offsetSet()` { #mvcmodelrow-offsetset }
public function offsetSet(
    mixed $offset,
    mixed $value
): void;
Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface #### `offsetUnset()` { #mvcmodelrow-offsetunset }
public function offsetUnset( mixed $offset ): void;
Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface #### `readAttribute()` { #mvcmodelrow-readattribute }
public function readAttribute( string $attribute );
Reads an attribute value by its name
echo $robot->readAttribute("name");
#### `setDirtyState()` { #mvcmodelrow-setdirtystate }
public function setDirtyState( int $dirtyState ): ModelInterface|bool;
Set the current object's state #### `toArray()` { #mvcmodelrow-toarray }
public function toArray(): array;
Returns the instance as an array representation #### `writeAttribute()` { #mvcmodelrow-writeattribute }
public function writeAttribute(
    string $attribute,
    mixed $value
): void;
Writes an attribute value by its name
$robot->writeAttribute("name", "Rosey");
## Mvc\Model\Transaction Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Transaction.zep){ .src-btn } Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Phalcon\Transaction is intended to be used with Phalcon_Model_Base. Phalcon Transactions should be created using Phalcon\Transaction\Manager.
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;

try {
    $manager = new Manager();

    $transaction = $manager->get();

    $robot = new Robots();

    $robot->setTransaction($transaction);

    $robot->name       = "WALL·E";
    $robot->created_at = date("Y-m-d");

    if ($robot->save() === false) {
        $transaction->rollback("Can't save robot");
    }

    $robotPart = new RobotParts();

    $robotPart->setTransaction($transaction);

    $robotPart->type = "head";

    if ($robotPart->save() === false) {
        $transaction->rollback("Can't save robot part");
    }

    $transaction->commit();
} catch(Failed $e) {
    echo "Failed, reason: ", $e->getMessage();
}
- **`Phalcon\Mvc\Model\Transaction`** — implements [`Phalcon\Mvc\Model\TransactionInterface`](#mvcmodeltransactioninterface)
__Uses__ `Phalcon\Db\Adapter\AdapterInterface` · `Phalcon\Di\DiInterface` · `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\TransactionInterface` · `Phalcon\Mvc\Model\Transaction\Failed` · `Phalcon\Mvc\Model\Transaction\ManagerInterface` { .api-uses } ### Method Summary ### Properties
protected bool $activeTransaction = false
protected AdapterInterface $connection
protected bool $isNewTransaction = true
protected ManagerInterface|null $manager = null
protected array $messages = []
protected bool $rollbackOnAbort = false
protected ModelInterface|null $rollbackRecord = null
protected bool $rollbackThrowException = false
### Methods
Public · 13
#### `__construct()` { #mvcmodeltransaction-__construct }
public function __construct(
    DiInterface $container,
    bool $autoBegin = false,
    string $service = "db"
);
Phalcon\Mvc\Model\Transaction constructor #### `begin()` { #mvcmodeltransaction-begin }
public function begin(): bool;
Starts the transaction #### `commit()` { #mvcmodeltransaction-commit }
public function commit(): bool;
Commits the transaction #### `getConnection()` { #mvcmodeltransaction-getconnection }
public function getConnection(): AdapterInterface;
Returns the connection related to transaction #### `getMessages()` { #mvcmodeltransaction-getmessages }
public function getMessages(): array;
Returns validations messages from last save try #### `isManaged()` { #mvcmodeltransaction-ismanaged }
public function isManaged(): bool;
Checks whether transaction is managed by a transaction manager #### `isValid()` { #mvcmodeltransaction-isvalid }
public function isValid(): bool;
Checks whether internal connection is under an active transaction #### `rollback()` { #mvcmodeltransaction-rollback }
public function rollback(
    string $rollbackMessage = null,
    ModelInterface $rollbackRecord = null
): bool;
Rollbacks the transaction #### `setIsNewTransaction()` { #mvcmodeltransaction-setisnewtransaction }
public function setIsNewTransaction( bool $isNew ): void;
Sets if is a reused transaction or new once #### `setRollbackOnAbort()` { #mvcmodeltransaction-setrollbackonabort }
public function setRollbackOnAbort( bool $rollbackOnAbort ): void;
Sets flag to rollback on abort the HTTP connection #### `setRollbackedRecord()` { #mvcmodeltransaction-setrollbackedrecord }
public function setRollbackedRecord( ModelInterface $record ): void;
Sets object which generates rollback action #### `setTransactionManager()` { #mvcmodeltransaction-settransactionmanager }
public function setTransactionManager( ManagerInterface $manager ): void;
Sets transaction manager related to the transaction #### `throwRollbackException()` { #mvcmodeltransaction-throwrollbackexception }
public function throwRollbackException( bool $status ): TransactionInterface;
Enables throwing exception ## Mvc\Model\TransactionInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/TransactionInterface.zep){ .src-btn } Interface for Phalcon\Mvc\Model\Transaction
- **`Phalcon\Mvc\Model\TransactionInterface`**
__Uses__ `Phalcon\Mvc\ModelInterface` · `Phalcon\Mvc\Model\Transaction\ManagerInterface` { .api-uses } ### Method Summary ### Methods
Public · 12
#### `begin()` { #mvcmodeltransactioninterface-begin }
public function begin(): bool;
Starts the transaction #### `commit()` { #mvcmodeltransactioninterface-commit }
public function commit(): bool;
Commits the transaction #### `getConnection()` { #mvcmodeltransactioninterface-getconnection }
public function getConnection(): \Phalcon\Db\Adapter\AdapterInterface;
Returns connection related to transaction #### `getMessages()` { #mvcmodeltransactioninterface-getmessages }
public function getMessages(): array;
Returns validations messages from last save try #### `isManaged()` { #mvcmodeltransactioninterface-ismanaged }
public function isManaged(): bool;
Checks whether transaction is managed by a transaction manager #### `isValid()` { #mvcmodeltransactioninterface-isvalid }
public function isValid(): bool;
Checks whether internal connection is under an active transaction #### `rollback()` { #mvcmodeltransactioninterface-rollback }
public function rollback(
    string $rollbackMessage = null,
    ModelInterface $rollbackRecord = null
): bool;
Rollbacks the transaction #### `setIsNewTransaction()` { #mvcmodeltransactioninterface-setisnewtransaction }
public function setIsNewTransaction( bool $isNew ): void;
Sets if is a reused transaction or new once #### `setRollbackOnAbort()` { #mvcmodeltransactioninterface-setrollbackonabort }
public function setRollbackOnAbort( bool $rollbackOnAbort ): void;
Sets flag to rollback on abort the HTTP connection #### `setRollbackedRecord()` { #mvcmodeltransactioninterface-setrollbackedrecord }
public function setRollbackedRecord( ModelInterface $record ): void;
Sets object which generates rollback action #### `setTransactionManager()` { #mvcmodeltransactioninterface-settransactionmanager }
public function setTransactionManager( ManagerInterface $manager ): void;
Sets transaction manager related to the transaction #### `throwRollbackException()` { #mvcmodeltransactioninterface-throwrollbackexception }
public function throwRollbackException( bool $status ): TransactionInterface;
Enables throwing exception ## Mvc\Model\Transaction\Exception Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Transaction/Exception.zep){ .src-btn } Phalcon\Mvc\Model\Transaction\Exception Exceptions thrown in Phalcon\Mvc\Model\Transaction will use this class
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\Transaction\Exception`** - [`Phalcon\Mvc\Model\Transaction\Failed`](#mvcmodeltransactionfailed)
## Mvc\Model\Transaction\Failed Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Transaction/Failed.zep){ .src-btn } Phalcon\Mvc\Model\Transaction\Failed This class will be thrown to exit a try/catch block for isolated transactions
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - [`Phalcon\Mvc\Model\Transaction\Exception`](#mvcmodeltransactionexception) - **`Phalcon\Mvc\Model\Transaction\Failed`**
__Uses__ `Phalcon\Messages\MessageInterface` · `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Properties
protected ModelInterface|null $record = null
### Methods
Public · 3
#### `__construct()` { #mvcmodeltransactionfailed-__construct }
public function __construct(
    string $message,
    ModelInterface $record = null
);
Phalcon\Mvc\Model\Transaction\Failed constructor #### `getRecord()` { #mvcmodeltransactionfailed-getrecord }
public function getRecord(): ModelInterface|null;
Returns validation record messages which stop the transaction #### `getRecordMessages()` { #mvcmodeltransactionfailed-getrecordmessages }
public function getRecordMessages(): array|string;
Returns validation record messages which stop the transaction ## Mvc\Model\Transaction\Manager Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Transaction/Manager.zep){ .src-btn } A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them. This class manages the objects that compose a transaction. A transaction produces a unique connection that is passed to every object part of the transaction.
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;

try {
   $transactionManager = new Manager();

   $transaction = $transactionManager->get();

   $robot = new Robots();

   $robot->setTransaction($transaction);

   $robot->name       = "WALL·E";
   $robot->created_at = date("Y-m-d");

   if ($robot->save() === false) {
       $transaction->rollback("Can't save robot");
   }

   $robotPart = new RobotParts();

   $robotPart->setTransaction($transaction);

   $robotPart->type = "head";

   if ($robotPart->save() === false) {
       $transaction->rollback("Can't save robot part");
   }

   $transaction->commit();
} catch (Failed $e) {
   echo "Failed, reason: ", $e->getMessage();
}
- **`Phalcon\Mvc\Model\Transaction\Manager`** — implements [`Phalcon\Mvc\Model\Transaction\ManagerInterface`](#mvcmodeltransactionmanagerinterface), [`Phalcon\Di\InjectionAwareInterface`](phalcon_di.md#diinjectionawareinterface)
__Uses__ `Phalcon\Di\Di` · `Phalcon\Di\DiInterface` · `Phalcon\Di\InjectionAwareInterface` · `Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable` · `Phalcon\Mvc\Model\Transaction` · `Phalcon\Mvc\Model\TransactionInterface` { .api-uses } ### Method Summary
public __construct( DiInterface $container = null ) Phalcon\Mvc\Model\Transaction\Manager constructor public void collectTransactions() Remove all the transactions from the manager public commit() Commits active transactions within the manager public TransactionInterface get( bool $autoBegin = true ) Returns a new \Phalcon\Mvc\Model\Transaction or an already created once public DiInterface getDI() Returns the dependency injection container public string getDbService() Returns the database service used to isolate the transaction public TransactionInterface getOrCreateTransaction( bool $autoBegin = true ) Create/Returns a new transaction or an existing one public bool getRollbackPendent() Check if the transaction manager is registering a shutdown function to public bool has() Checks whether the manager has an active transaction public void notifyCommit( TransactionInterface $transaction ) Notifies the manager about a committed transaction public void notifyRollback( TransactionInterface $transaction ) Notifies the manager about a rollbacked transaction public void rollback( bool $collect = true ) Rollbacks active transactions within the manager public void rollbackPendent() Rollbacks active transactions within the manager public void setDI( DiInterface $container ) Sets the dependency injection container public ManagerInterface setDbService( string $service ) Sets the database service used to run the isolated transactions public ManagerInterface setRollbackPendent( bool $rollbackPendent ) Set if the transaction manager must register a shutdown function to clean protected void collectTransaction( TransactionInterface $transaction ) Removes transactions from the TransactionManager
### Properties
protected DiInterface|null $container
protected bool $initialized = false
protected int $number = 0
protected bool $rollbackPendent = true
protected string $service = "db"
protected array $transactions = []
### Methods
Public · 16
#### `__construct()` { #mvcmodeltransactionmanager-__construct }
public function __construct( DiInterface $container = null );
Phalcon\Mvc\Model\Transaction\Manager constructor #### `collectTransactions()` { #mvcmodeltransactionmanager-collecttransactions }
public function collectTransactions(): void;
Remove all the transactions from the manager #### `commit()` { #mvcmodeltransactionmanager-commit }
public function commit();
Commits active transactions within the manager #### `get()` { #mvcmodeltransactionmanager-get }
public function get( bool $autoBegin = true ): TransactionInterface;
Returns a new \Phalcon\Mvc\Model\Transaction or an already created once This method registers a shutdown function to rollback active connections #### `getDI()` { #mvcmodeltransactionmanager-getdi }
public function getDI(): DiInterface;
Returns the dependency injection container #### `getDbService()` { #mvcmodeltransactionmanager-getdbservice }
public function getDbService(): string;
Returns the database service used to isolate the transaction #### `getOrCreateTransaction()` { #mvcmodeltransactionmanager-getorcreatetransaction }
public function getOrCreateTransaction( bool $autoBegin = true ): TransactionInterface;
Create/Returns a new transaction or an existing one #### `getRollbackPendent()` { #mvcmodeltransactionmanager-getrollbackpendent }
public function getRollbackPendent(): bool;
Check if the transaction manager is registering a shutdown function to clean up pendent transactions #### `has()` { #mvcmodeltransactionmanager-has }
public function has(): bool;
Checks whether the manager has an active transaction #### `notifyCommit()` { #mvcmodeltransactionmanager-notifycommit }
public function notifyCommit( TransactionInterface $transaction ): void;
Notifies the manager about a committed transaction #### `notifyRollback()` { #mvcmodeltransactionmanager-notifyrollback }
public function notifyRollback( TransactionInterface $transaction ): void;
Notifies the manager about a rollbacked transaction #### `rollback()` { #mvcmodeltransactionmanager-rollback }
public function rollback( bool $collect = true ): void;
Rollbacks active transactions within the manager Collect will remove the transaction from the manager #### `rollbackPendent()` { #mvcmodeltransactionmanager-rollbackpendent }
public function rollbackPendent(): void;
Rollbacks active transactions within the manager #### `setDI()` { #mvcmodeltransactionmanager-setdi }
public function setDI( DiInterface $container ): void;
Sets the dependency injection container #### `setDbService()` { #mvcmodeltransactionmanager-setdbservice }
public function setDbService( string $service ): ManagerInterface;
Sets the database service used to run the isolated transactions #### `setRollbackPendent()` { #mvcmodeltransactionmanager-setrollbackpendent }
public function setRollbackPendent( bool $rollbackPendent ): ManagerInterface;
Set if the transaction manager must register a shutdown function to clean up pendent transactions
Protected · 1
#### `collectTransaction()` { #mvcmodeltransactionmanager-collecttransaction }
protected function collectTransaction( TransactionInterface $transaction ): void;
Removes transactions from the TransactionManager ## Mvc\Model\Transaction\ManagerInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/Transaction/ManagerInterface.zep){ .src-btn } Phalcon\Mvc\Model\Transaction\ManagerInterface Interface for Phalcon\Mvc\Model\Transaction\Manager
- **`Phalcon\Mvc\Model\Transaction\ManagerInterface`**
__Uses__ `Phalcon\Mvc\Model\TransactionInterface` { .api-uses } ### Method Summary ### Methods
Public · 12
#### `collectTransactions()` { #mvcmodeltransactionmanagerinterface-collecttransactions }
public function collectTransactions(): void;
Remove all the transactions from the manager #### `commit()` { #mvcmodeltransactionmanagerinterface-commit }
public function commit();
Commits active transactions within the manager #### `get()` { #mvcmodeltransactionmanagerinterface-get }
public function get( bool $autoBegin = true ): TransactionInterface;
Returns a new \Phalcon\Mvc\Model\Transaction or an already created once #### `getDbService()` { #mvcmodeltransactionmanagerinterface-getdbservice }
public function getDbService(): string;
Returns the database service used to isolate the transaction #### `getRollbackPendent()` { #mvcmodeltransactionmanagerinterface-getrollbackpendent }
public function getRollbackPendent(): bool;
Check if the transaction manager is registering a shutdown function to clean up pendent transactions #### `has()` { #mvcmodeltransactionmanagerinterface-has }
public function has(): bool;
Checks whether manager has an active transaction #### `notifyCommit()` { #mvcmodeltransactionmanagerinterface-notifycommit }
public function notifyCommit( TransactionInterface $transaction ): void;
Notifies the manager about a committed transaction #### `notifyRollback()` { #mvcmodeltransactionmanagerinterface-notifyrollback }
public function notifyRollback( TransactionInterface $transaction ): void;
Notifies the manager about a rollbacked transaction #### `rollback()` { #mvcmodeltransactionmanagerinterface-rollback }
public function rollback( bool $collect = false ): void;
Rollbacks active transactions within the manager Collect will remove transaction from the manager #### `rollbackPendent()` { #mvcmodeltransactionmanagerinterface-rollbackpendent }
public function rollbackPendent(): void;
Rollbacks active transactions within the manager #### `setDbService()` { #mvcmodeltransactionmanagerinterface-setdbservice }
public function setDbService( string $service ): ManagerInterface;
Sets the database service used to run the isolated transactions #### `setRollbackPendent()` { #mvcmodeltransactionmanagerinterface-setrollbackpendent }
public function setRollbackPendent( bool $rollbackPendent ): ManagerInterface;
Set if the transaction manager must register a shutdown function to clean up pendent transactions ## Mvc\Model\ValidationFailed Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Model/ValidationFailed.zep){ .src-btn } Phalcon\Mvc\Model\ValidationFailed This exception is generated when a model fails to save a record Phalcon\Mvc\Model must be set up to have this behavior
- `\Exception` - [`Phalcon\Mvc\Model\Exception`](#mvcmodelexception) - **`Phalcon\Mvc\Model\ValidationFailed`**
__Uses__ `Phalcon\Messages\Message` · `Phalcon\Mvc\ModelInterface` { .api-uses } ### Method Summary ### Properties
protected ModelInterface $model
protected array $validationMessages = []
### Methods
Public · 3
#### `__construct()` { #mvcmodelvalidationfailed-__construct }
public function __construct(
    ModelInterface $model,
    array $validationMessages
);
Phalcon\Mvc\Model\ValidationFailed constructor #### `getMessages()` { #mvcmodelvalidationfailed-getmessages }
public function getMessages(): Message[];
Returns the complete group of messages produced in the validation #### `getModel()` { #mvcmodelvalidationfailed-getmodel }
public function getModel(): ModelInterface;
Returns the model that generated the messages ## Mvc\ModuleDefinitionInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/ModuleDefinitionInterface.zep){ .src-btn } This interface must be implemented by class module definitions
- **`Phalcon\Mvc\ModuleDefinitionInterface`**
__Uses__ `Phalcon\Di\DiInterface` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `registerAutoloaders()` { #mvcmoduledefinitioninterface-registerautoloaders }
public function registerAutoloaders( DiInterface $container = null );
Registers an autoloader related to the module #### `registerServices()` { #mvcmoduledefinitioninterface-registerservices }
public function registerServices( DiInterface $container );
Registers services related to the module ## Mvc\Router Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router.zep){ .src-btn } Phalcon\Mvc\Router Phalcon\Mvc\Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request
use Phalcon\Mvc\Router;

$router = new Router();

$router->add(
    "/documentation/{chapter}/{name}\.{type:[a-z]+}",
    [
        "controller" => "documentation",
        "action"     => "show",
    ]
);

$router->handle(
    "/documentation/1/examples.html"
);

echo $router->getControllerName();
- `stdClass` - [`Phalcon\Di\AbstractInjectionAware`](phalcon_di.md#diabstractinjectionaware) - **`Phalcon\Mvc\Router`** — implements [`Phalcon\Mvc\RouterInterface`](#mvcrouterinterface), [`Phalcon\Events\EventsAwareInterface`](phalcon_events.md#eventseventsawareinterface) - [`Phalcon\Mvc\Router\Annotations`](#mvcrouterannotations)
__Uses__ `Phalcon\Cache\Adapter\AdapterInterface` · `Phalcon\Config\ConfigInterface` · `Phalcon\Di\AbstractInjectionAware` · `Phalcon\Di\DiInterface` · `Phalcon\Events\EventsAwareInterface` · `Phalcon\Events\ManagerInterface` · `Phalcon\Http\RequestInterface` · `Phalcon\Mvc\Router\Exception` · `Phalcon\Mvc\Router\Exceptions\BeforeMatchNotCallable` · `Phalcon\Mvc\Router\Exceptions\ConfigKeyMustBeArray` · `Phalcon\Mvc\Router\Exceptions\EmptyGroupOfRoutes` · `Phalcon\Mvc\Router\Exceptions\GroupRoutesMustBeArray` · `Phalcon\Mvc\Router\Exceptions\InvalidConfigSource` · `Phalcon\Mvc\Router\Exceptions\InvalidNotFoundPaths` · `Phalcon\Mvc\Router\Exceptions\InvalidRoutePosition` · `Phalcon\Mvc\Router\Exceptions\MissingGroupRouteKey` · `Phalcon\Mvc\Router\Exceptions\MissingRouteConfigKey` · `Phalcon\Mvc\Router\Exceptions\RequestServiceUnavailable` · `Phalcon\Mvc\Router\Exceptions\UnknownHttpMethod` · `Phalcon\Mvc\Router\Exceptions\WrongPathsKey` · `Phalcon\Mvc\Router\Group` · `Phalcon\Mvc\Router\GroupInterface` · `Phalcon\Mvc\Router\Route` · `Phalcon\Mvc\Router\RouteInterface` { .api-uses } ### Method Summary
public __construct( bool $defaultRoutes = true ) Phalcon\Mvc\Router constructor public RouteInterface add(string $pattern,mixed $paths = null,mixed $httpMethods = null,int $position = Router::POSITION_LAST) Adds a route to the router without any HTTP constraint public RouteInterface addConnect(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is CONNECT public RouteInterface addDelete(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is DELETE public RouteInterface addGet(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is GET public RouteInterface addHead(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is HEAD public RouteInterface addOptions(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Add a route to the router that only match if the HTTP method is OPTIONS public RouteInterface addPatch(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PATCH public RouteInterface addPost(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is POST public RouteInterface addPurge(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PURGE public RouteInterface addPut(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PUT public RouteInterface addTrace(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is TRACE public static attach(RouteInterface $route,int $position = Router::POSITION_LAST) Attach Route object to the routes stack. public array buildDispatcherDump() Produces a pure-data array describing every piece of state needed public void clear() Removes all the pre-defined routes public void dumpDispatcher( string $path ) File-shaped helper around buildDispatcherDump(). Writes the dump as public string getActionName() Returns the processed action name public string getControllerName() Returns the processed controller name public array getDefaults() Returns an array of default parameters public ManagerInterface|null getEventsManager() Returns the internal event manager public array getKeyRouteIds() public array getKeyRouteNames() public RouteInterface|null getMatchedRoute() Returns the route that matches the handled URI public array getMatches() Returns the sub expressions in the regular expression matched public array getMethodRoutes() Returns the routes indexed by HTTP method. public string getModuleName() Returns the processed module name public string getNamespaceName() Returns the processed namespace name public array getParams() Returns the processed parameters public string getRewriteUri() Get rewrite info. This info is read from $_GET["_url"]. public RouteInterface|bool getRouteById( mixed $routeId ) Returns a route object by its id public RouteInterface|bool getRouteByName( string $name ) Returns a route object by its name public RouteInterface[] getRoutes() Returns all the routes defined in the router public void handle( string $uri ) Handles routing information received from the rewrite engine public bool isExactControllerName() Returns whether controller name should not be mangled public void loadDispatcher( string $path ) File-shaped helper around loadDispatcherFromArray(). Includes the public void loadDispatcherFromArray( array $dump ) Inverse of buildDispatcherDump(). Reconstructs every Route from the public static loadFromConfig( mixed $config ) Loads routes from an array or Phalcon\Config\Config instance. public static mount( GroupInterface $group ) Mounts a group of routes in the router public static notFound( mixed $paths ) Set a group of paths to be returned when none of the defined routes are public static removeExtraSlashes( bool $remove ) Set whether router must remove the extra slashes in the handled routes public static setDefaultAction( string $actionName ) Sets the default action name public static setDefaultController( string $controllerName ) Sets the default controller name public static setDefaultModule( string $moduleName ) Sets the name of the default module public static setDefaultNamespace( string $namespaceName ) Sets the name of the default namespace public static setDefaults( array $defaults ) Sets an array of default paths. If a route is missing a path the router public void setEventsManager( ManagerInterface $eventsManager ) Sets the events manager public static setKeyRouteIds( array $routeIds ) public static setKeyRouteNames( array $routeNames ) public static setUriSource( int $uriSource ) Sets the URI source. One of the URI_SOURCE_* constants public void useCache(CacheAdapterInterface $cache,string $key = "phalcon.router.dispatcher") Cache-instance convenience wrapper. On cache hit, restores the public bool wasMatched() Checks if the router matches any of the defined routes protected void addRouteFromConfig( array $routeData ) Adds a single route from a config array entry. Used by loadFromConfig. protected string extractRealUri( string $uri ) protected void mountGroupFromConfig( array $groupData ) Builds a Group from a config entry and mounts it. Used by loadFromConfig. protected void rebuildMethodIndex()
### Constants
int POSITION_FIRST = 0
int POSITION_LAST = 1
int REGEX_CHUNK_SIZE = 10 Number of alternatives per combined-regex chunk. Empirically derived (FastRoute uses ~10) - keeps each chunk below PCRE's optimizer cliff.
int URI_SOURCE_GET_URL = 0
int URI_SOURCE_SERVER_REQUEST_URI = 1
### Properties
protected string $action = ""
protected array $candidatesByMethod = [] Pre-merged per-method candidate buckets in attach order. For each HTTP method seen on any registered route, the bucket contains the method-specific routes followed by the "*" (no-constraint) routes. The "*" key itself holds only the no-constraint routes - used when the request method has no specific bucket. Built in rebuildMethodIndex(); consumed by handle() in reverse.
protected array $combinedRegexByMethod = [] Combined PCRE pattern per method bucket (chunked list of strings). Each chunk uses (?|...) branch reset and (*:N) mark labels. Built only when the bucket meets gating: no hostname routes; standard pattern shape.
protected array $combinedRegexDisabled = [] Boolean per method bucket: true when the combined regex cannot be built (hostname route present, exotic pattern shape, etc.).
protected array $combinedRegexMarkMap = [] Map from MARK label back to the route index in candidatesByMethod[method]. One per chunk. combinedRegexMarkMap[method][chunkIdx][markLabel] = routeIdx
protected string $controller = ""
protected string $defaultAction = ""
protected string $defaultController = ""
protected string $defaultModule = ""
protected string $defaultNamespace = ""
protected array $defaultParams = []
protected ManagerInterface|null $eventsManager
protected array $hostnameByMethod = [] Per-method buckets of routes with hostname constraints, grouped by raw hostname string. Routes are referenced by their index into candidatesByMethod[method]. Built in rebuildMethodIndex(). Shape: hostnameByMethod[method][hostname] = list of route indices.
protected array $hostnameLessByMethod = [] Per-method indices of routes without a hostname constraint, in attach order. Shape: hostnameLessByMethod[method] = list of route indices into candidatesByMethod[method].
protected array $keyRouteIds = []
protected array $keyRouteNames = []
protected RouteInterface|null $matchedRoute = null
protected array $matches = []
protected array $methodRoutes = []
protected bool $methodRoutesDirty = true
protected string $module = ""
protected string $namespaceName = ""
protected array|string|null $notFoundPaths = null
protected array $params = []
protected CacheAdapterInterface|null $pendingCache = null Lazy-write cache target set by useCache(). When non-null, handle() writes buildDispatcherDump() to this cache after a successful rebuild on cache miss, then clears the property to skip subsequent writes.
protected string $pendingCacheKey = ""
protected bool $removeExtraSlashes = false
protected array $routeMeta = [] Single-source per-route metadata cache. One entry per route, keyed by the route's intrinsic id. Replaces the previous per-method-bucket replication of metadata arrays. Built once in rebuildMethodIndex(). Shape: routeMeta[routeId] = [ "pattern": string, // compiled pattern "isRegex": bool, "hostname": string|null, "hostRegex": string|null, "beforeMatch": callable|null ]
protected array $routes = []
protected array $staticByMethod = [] Static-route hash, populated by rebuildMethodIndex(). For each method bucket (including "*"), maps URI => list of routes whose compiled pattern is a literal string equal to that URI.
protected array $staticShadowedByMethod = [] Shadow-detection map. If staticShadowedByMethod[method][uri] is set, the static URI in that bucket is shadowed by a later-attached regex route - the fast path MUST NOT be used; fall through to the dynamic loop so the regex wins (reverse-iteration semantics).
protected int $uriSource = self::URI_SOURCE_GET_URL
protected bool $wasMatched = false
### Methods
Public · 51
#### `__construct()` { #mvcrouter-__construct }
public function __construct( bool $defaultRoutes = true );
Phalcon\Mvc\Router constructor #### `add()` { #mvcrouter-add }
public function add(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router without any HTTP constraint
use Phalcon\Mvc\Router;

$router->add("/about", "About::index");

$router->add(
    "/about",
    "About::index",
    ["GET", "POST"]
);

$router->add(
    "/about",
    "About::index",
    ["GET", "POST"],
    Router::POSITION_FIRST
);
#### `addConnect()` { #mvcrouter-addconnect }
public function addConnect(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is CONNECT #### `addDelete()` { #mvcrouter-adddelete }
public function addDelete(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is DELETE #### `addGet()` { #mvcrouter-addget }
public function addGet(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is GET #### `addHead()` { #mvcrouter-addhead }
public function addHead(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is HEAD #### `addOptions()` { #mvcrouter-addoptions }
public function addOptions(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Add a route to the router that only match if the HTTP method is OPTIONS #### `addPatch()` { #mvcrouter-addpatch }
public function addPatch(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PATCH #### `addPost()` { #mvcrouter-addpost }
public function addPost(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is POST #### `addPurge()` { #mvcrouter-addpurge }
public function addPurge(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support) #### `addPut()` { #mvcrouter-addput }
public function addPut(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PUT #### `addTrace()` { #mvcrouter-addtrace }
public function addTrace(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is TRACE #### `attach()` { #mvcrouter-attach }
public function attach(
    RouteInterface $route,
    int $position = Router::POSITION_LAST
): static;
Attach Route object to the routes stack.
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Route;

class CustomRoute extends Route {
     // ...
}

$router = new Router();

$router->attach(
    new CustomRoute("/about", "About::index", ["GET", "HEAD"]),
    Router::POSITION_FIRST
);
#### `buildDispatcherDump()` { #mvcrouter-builddispatcherdump }
public function buildDispatcherDump(): array;
Produces a pure-data array describing every piece of state needed to reconstruct this router. The returned array is var_export-able (no objects, no closures). Used by dumpDispatcher() and by Phalcon\Cache integration via useCache(). Throws when a route has a Closure beforeMatch or converter - those cannot be cached. #### `clear()` { #mvcrouter-clear }
public function clear(): void;
Removes all the pre-defined routes #### `dumpDispatcher()` { #mvcrouter-dumpdispatcher }
public function dumpDispatcher( string $path ): void;
File-shaped helper around buildDispatcherDump(). Writes the dump as a `
public function getActionName(): string;
Returns the processed action name #### `getControllerName()` { #mvcrouter-getcontrollername }
public function getControllerName(): string;
Returns the processed controller name #### `getDefaults()` { #mvcrouter-getdefaults }
public function getDefaults(): array;
Returns an array of default parameters #### `getEventsManager()` { #mvcrouter-geteventsmanager }
public function getEventsManager(): ManagerInterface|null;
Returns the internal event manager #### `getKeyRouteIds()` { #mvcrouter-getkeyrouteids }
public function getKeyRouteIds(): array;
#### `getKeyRouteNames()` { #mvcrouter-getkeyroutenames }
public function getKeyRouteNames(): array;
#### `getMatchedRoute()` { #mvcrouter-getmatchedroute }
public function getMatchedRoute(): RouteInterface|null;
Returns the route that matches the handled URI #### `getMatches()` { #mvcrouter-getmatches }
public function getMatches(): array;
Returns the sub expressions in the regular expression matched #### `getMethodRoutes()` { #mvcrouter-getmethodroutes }
public function getMethodRoutes(): array;
Returns the routes indexed by HTTP method. Routes with no HTTP constraint are stored under the "*" key. #### `getModuleName()` { #mvcrouter-getmodulename }
public function getModuleName(): string;
Returns the processed module name #### `getNamespaceName()` { #mvcrouter-getnamespacename }
public function getNamespaceName(): string;
Returns the processed namespace name #### `getParams()` { #mvcrouter-getparams }
public function getParams(): array;
Returns the processed parameters #### `getRewriteUri()` { #mvcrouter-getrewriteuri }
public function getRewriteUri(): string;
Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read #### `getRouteById()` { #mvcrouter-getroutebyid }
public function getRouteById( mixed $routeId ): RouteInterface|bool;
Returns a route object by its id #### `getRouteByName()` { #mvcrouter-getroutebyname }
public function getRouteByName( string $name ): RouteInterface|bool;
Returns a route object by its name #### `getRoutes()` { #mvcrouter-getroutes }
public function getRoutes(): RouteInterface[];
Returns all the routes defined in the router #### `handle()` { #mvcrouter-handle }
public function handle( string $uri ): void;
Handles routing information received from the rewrite engine
// Passing a URL
$router->handle("/posts/edit/1");
#### `isExactControllerName()` { #mvcrouter-isexactcontrollername }
public function isExactControllerName(): bool;
Returns whether controller name should not be mangled #### `loadDispatcher()` { #mvcrouter-loaddispatcher }
public function loadDispatcher( string $path ): void;
File-shaped helper around loadDispatcherFromArray(). Includes the file (opcache-friendly) and forwards the return value. #### `loadDispatcherFromArray()` { #mvcrouter-loaddispatcherfromarray }
public function loadDispatcherFromArray( array $dump ): void;
Inverse of buildDispatcherDump(). Reconstructs every Route from the scalar `routes` entries (preserving subclass and routeId), restores every index, and marks the indexes clean so handle() skips rebuild. #### `loadFromConfig()` { #mvcrouter-loadfromconfig }
public function loadFromConfig( mixed $config ): static;
Loads routes from an array or Phalcon\Config\Config instance.
$router->loadFromConfig(
     [
         'routes' => [
             [
                 'method'  => 'get',
                 'pattern' => '/users',
                 'paths'   => 'Users::index',
             ],
         ],
     ]
 );
#### `mount()` { #mvcrouter-mount }
public function mount( GroupInterface $group ): static;
Mounts a group of routes in the router #### `notFound()` { #mvcrouter-notfound }
public function notFound( mixed $paths ): static;
Set a group of paths to be returned when none of the defined routes are matched #### `removeExtraSlashes()` { #mvcrouter-removeextraslashes }
public function removeExtraSlashes( bool $remove ): static;
Set whether router must remove the extra slashes in the handled routes #### `setDefaultAction()` { #mvcrouter-setdefaultaction }
public function setDefaultAction( string $actionName ): static;
Sets the default action name #### `setDefaultController()` { #mvcrouter-setdefaultcontroller }
public function setDefaultController( string $controllerName ): static;
Sets the default controller name #### `setDefaultModule()` { #mvcrouter-setdefaultmodule }
public function setDefaultModule( string $moduleName ): static;
Sets the name of the default module #### `setDefaultNamespace()` { #mvcrouter-setdefaultnamespace }
public function setDefaultNamespace( string $namespaceName ): static;
Sets the name of the default namespace @parma string namespaceName #### `setDefaults()` { #mvcrouter-setdefaults }
public function setDefaults( array $defaults ): static;
Sets an array of default paths. If a route is missing a path the router will use the defined here. This method must not be used to set a 404 route
$router->setDefaults(
    [
        "module" => "common",
        "action" => "index",
    ]
);
#### `setEventsManager()` { #mvcrouter-seteventsmanager }
public function setEventsManager( ManagerInterface $eventsManager ): void;
Sets the events manager #### `setKeyRouteIds()` { #mvcrouter-setkeyrouteids }
public function setKeyRouteIds( array $routeIds ): static;
#### `setKeyRouteNames()` { #mvcrouter-setkeyroutenames }
public function setKeyRouteNames( array $routeNames ): static;
#### `setUriSource()` { #mvcrouter-seturisource }
public function setUriSource( int $uriSource ): static;
Sets the URI source. One of the URI_SOURCE_* constants
$router->setUriSource(
    Router::URI_SOURCE_SERVER_REQUEST_URI
);
#### `useCache()` { #mvcrouter-usecache }
public function useCache(
    CacheAdapterInterface $cache,
    string $key = "phalcon.router.dispatcher"
): void;
Cache-instance convenience wrapper. On cache hit, restores the dispatcher immediately. On miss, defers cache population until the next handle() completes - at which point buildDispatcherDump() is written to the cache key. #### `wasMatched()` { #mvcrouter-wasmatched }
public function wasMatched(): bool;
Checks if the router matches any of the defined routes
Protected · 4
#### `addRouteFromConfig()` { #mvcrouter-addroutefromconfig }
protected function addRouteFromConfig( array $routeData ): void;
Adds a single route from a config array entry. Used by loadFromConfig. #### `extractRealUri()` { #mvcrouter-extractrealuri }
protected function extractRealUri( string $uri ): string;
#### `mountGroupFromConfig()` { #mvcrouter-mountgroupfromconfig }
protected function mountGroupFromConfig( array $groupData ): void;
Builds a Group from a config entry and mounts it. Used by loadFromConfig. #### `rebuildMethodIndex()` { #mvcrouter-rebuildmethodindex }
protected function rebuildMethodIndex(): void;
## Mvc\RouterInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/RouterInterface.zep){ .src-btn } Interface for Phalcon\Mvc\Router
- **`Phalcon\Mvc\RouterInterface`**
__Uses__ `Phalcon\Mvc\Router\GroupInterface` · `Phalcon\Mvc\Router\RouteInterface` { .api-uses } ### Method Summary
public RouteInterface add(string $pattern,mixed $paths = null,mixed $httpMethods = null,int $position = Router::POSITION_LAST) Adds a route to the router on any HTTP method public RouteInterface addConnect(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is CONNECT public RouteInterface addDelete(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is DELETE public RouteInterface addGet(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is GET public RouteInterface addHead(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is HEAD public RouteInterface addOptions(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Add a route to the router that only match if the HTTP method is OPTIONS public RouteInterface addPatch(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PATCH public RouteInterface addPost(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is POST public RouteInterface addPurge(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PURGE public RouteInterface addPut(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PUT public RouteInterface addTrace(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is TRACE public RouterInterface attach(RouteInterface $route,int $position = Router::POSITION_LAST) Attach Route object to the routes stack. public void clear() Removes all the defined routes public string getActionName() Returns processed action name public string getControllerName() Returns processed controller name public RouteInterface|null getMatchedRoute() Returns the route that matches the handled URI public array getMatches() Return the sub expressions in the regular expression matched public string getModuleName() Returns processed module name public string getNamespaceName() Returns processed namespace name public array getParams() Returns processed extra params public RouteInterface|bool getRouteById( mixed $routeId ) Returns a route object by its id public RouteInterface|bool getRouteByName( string $name ) Returns a route object by its name public RouteInterface[] getRoutes() Return all the routes defined in the router public void handle( string $uri ) Handles routing information received from the rewrite engine public RouterInterface loadFromConfig( mixed $config ) Loads routes from an array or Phalcon\Config\Config instance. public RouterInterface mount( GroupInterface $group ) Mounts a group of routes in the router public RouterInterface setDefaultAction( string $actionName ) Sets the default action name public RouterInterface setDefaultController( string $controllerName ) Sets the default controller name public RouterInterface setDefaultModule( string $moduleName ) Sets the name of the default module public RouterInterface setDefaults( array $defaults ) Sets an array of default paths public bool wasMatched() Check if the router matches any of the defined routes
### Methods
Public · 31
#### `add()` { #mvcrouterinterface-add }
public function add(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router on any HTTP method #### `addConnect()` { #mvcrouterinterface-addconnect }
public function addConnect(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is CONNECT #### `addDelete()` { #mvcrouterinterface-adddelete }
public function addDelete(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is DELETE #### `addGet()` { #mvcrouterinterface-addget }
public function addGet(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is GET #### `addHead()` { #mvcrouterinterface-addhead }
public function addHead(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is HEAD #### `addOptions()` { #mvcrouterinterface-addoptions }
public function addOptions(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Add a route to the router that only match if the HTTP method is OPTIONS #### `addPatch()` { #mvcrouterinterface-addpatch }
public function addPatch(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PATCH #### `addPost()` { #mvcrouterinterface-addpost }
public function addPost(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is POST #### `addPurge()` { #mvcrouterinterface-addpurge }
public function addPurge(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support) #### `addPut()` { #mvcrouterinterface-addput }
public function addPut(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PUT #### `addTrace()` { #mvcrouterinterface-addtrace }
public function addTrace(
    string $pattern,
    mixed $paths = null,
    int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is TRACE #### `attach()` { #mvcrouterinterface-attach }
public function attach(
    RouteInterface $route,
    int $position = Router::POSITION_LAST
): RouterInterface;
Attach Route object to the routes stack. #### `clear()` { #mvcrouterinterface-clear }
public function clear(): void;
Removes all the defined routes #### `getActionName()` { #mvcrouterinterface-getactionname }
public function getActionName(): string;
Returns processed action name #### `getControllerName()` { #mvcrouterinterface-getcontrollername }
public function getControllerName(): string;
Returns processed controller name #### `getMatchedRoute()` { #mvcrouterinterface-getmatchedroute }
public function getMatchedRoute(): RouteInterface|null;
Returns the route that matches the handled URI #### `getMatches()` { #mvcrouterinterface-getmatches }
public function getMatches(): array;
Return the sub expressions in the regular expression matched #### `getModuleName()` { #mvcrouterinterface-getmodulename }
public function getModuleName(): string;
Returns processed module name #### `getNamespaceName()` { #mvcrouterinterface-getnamespacename }
public function getNamespaceName(): string;
Returns processed namespace name #### `getParams()` { #mvcrouterinterface-getparams }
public function getParams(): array;
Returns processed extra params #### `getRouteById()` { #mvcrouterinterface-getroutebyid }
public function getRouteById( mixed $routeId ): RouteInterface|bool;
Returns a route object by its id #### `getRouteByName()` { #mvcrouterinterface-getroutebyname }
public function getRouteByName( string $name ): RouteInterface|bool;
Returns a route object by its name #### `getRoutes()` { #mvcrouterinterface-getroutes }
public function getRoutes(): RouteInterface[];
Return all the routes defined in the router #### `handle()` { #mvcrouterinterface-handle }
public function handle( string $uri ): void;
Handles routing information received from the rewrite engine #### `loadFromConfig()` { #mvcrouterinterface-loadfromconfig }
public function loadFromConfig( mixed $config ): RouterInterface;
Loads routes from an array or Phalcon\Config\Config instance. #### `mount()` { #mvcrouterinterface-mount }
public function mount( GroupInterface $group ): RouterInterface;
Mounts a group of routes in the router #### `setDefaultAction()` { #mvcrouterinterface-setdefaultaction }
public function setDefaultAction( string $actionName ): RouterInterface;
Sets the default action name #### `setDefaultController()` { #mvcrouterinterface-setdefaultcontroller }
public function setDefaultController( string $controllerName ): RouterInterface;
Sets the default controller name #### `setDefaultModule()` { #mvcrouterinterface-setdefaultmodule }
public function setDefaultModule( string $moduleName ): RouterInterface;
Sets the name of the default module #### `setDefaults()` { #mvcrouterinterface-setdefaults }
public function setDefaults( array $defaults ): RouterInterface;
Sets an array of default paths #### `wasMatched()` { #mvcrouterinterface-wasmatched }
public function wasMatched(): bool;
Check if the router matches any of the defined routes ## Mvc\Router\Annotations Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Annotations.zep){ .src-btn } Phalcon\Mvc\Router\Annotations A router that reads routes annotations from classes/resources
use Phalcon\Mvc\Router\Annotations;

$di->setShared(
    "router",
    function() {
        // Use the annotations router
        $router = new Annotations(false);

        // This will do the same as above but only if the handled uri starts with /robots
        $router->addResource("Robots", "/robots");

        return $router;
    }
);
- `stdClass` - [`Phalcon\Di\AbstractInjectionAware`](phalcon_di.md#diabstractinjectionaware) - [`Phalcon\Mvc\Router`](#mvcrouter) - **`Phalcon\Mvc\Router\Annotations`**
__Uses__ `Phalcon\Annotations\Annotation` · `Phalcon\Di\DiInterface` · `Phalcon\Mvc\Router` · `Phalcon\Mvc\Router\Exceptions\AnnotationsServiceUnavailable` · `Phalcon\Mvc\Router\Exceptions\InvalidCallbackParameter` { .api-uses } ### Method Summary ### Properties
protected callable|string|null $actionPreformatCallback = null
protected string $actionSuffix = "Action"
protected string $controllerSuffix = "Controller"
protected array $handlers = []
protected string $routePrefix = ""
### Methods
Public · 10
#### `addModuleResource()` { #mvcrouterannotations-addmoduleresource }
public function addModuleResource(
    string $module,
    string $handler,
    string $prefix = null
): static;
Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module #### `addResource()` { #mvcrouterannotations-addresource }
public function addResource(
    string $handler,
    string $prefix = null
): static;
Adds a resource to the annotations handler A resource is a class that contains routing annotations #### `getActionPreformatCallback()` { #mvcrouterannotations-getactionpreformatcallback }
public function getActionPreformatCallback();
#### `getResources()` { #mvcrouterannotations-getresources }
public function getResources(): array;
Return the registered resources #### `handle()` { #mvcrouterannotations-handle }
public function handle( string $uri ): void;
Produce the routing parameters from the rewrite information #### `processActionAnnotation()` { #mvcrouterannotations-processactionannotation }
public function processActionAnnotation(
    string $module,
    string $namespaceName,
    string $controller,
    string $action,
    Annotation $annotation
): void;
Checks for annotations in the public methods of the controller #### `processControllerAnnotation()` { #mvcrouterannotations-processcontrollerannotation }
public function processControllerAnnotation(
    string $handler,
    Annotation $annotation
);
Checks for annotations in the controller docblock #### `setActionPreformatCallback()` { #mvcrouterannotations-setactionpreformatcallback }
public function setActionPreformatCallback( mixed $callback = null ): self;
Sets the action preformat callback $action here already without suffix 'Action'
// Array as callback
$annotationRouter->setActionPreformatCallback(
     [
         new Uncamelize(),
         '__invoke'
     ]
 );

// Function as callback
$annotationRouter->setActionPreformatCallback(
    function ($action) {
        return $action;
    }
);

// String as callback
$annotationRouter->setActionPreformatCallback('strtolower');

// If empty method constructor called [null], sets uncamelize with - delimiter
$annotationRouter->setActionPreformatCallback();
#### `setActionSuffix()` { #mvcrouterannotations-setactionsuffix }
public function setActionSuffix( string $actionSuffix ): self;
Changes the action method suffix #### `setControllerSuffix()` { #mvcrouterannotations-setcontrollersuffix }
public function setControllerSuffix( string $controllerSuffix ): self;
Changes the controller class suffix ## Mvc\Router\Exception Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exception.zep){ .src-btn } Phalcon\Mvc\Router\Exception Exceptions thrown in Phalcon\Mvc\Router will use this class
- `\Exception` - **`Phalcon\Mvc\Router\Exception`** - [`Phalcon\Mvc\Router\Exceptions\AnnotationsServiceUnavailable`](#mvcrouterexceptionsannotationsserviceunavailable) - [`Phalcon\Mvc\Router\Exceptions\BeforeMatchNotCallable`](#mvcrouterexceptionsbeforematchnotcallable) - [`Phalcon\Mvc\Router\Exceptions\ConfigKeyMustBeArray`](#mvcrouterexceptionsconfigkeymustbearray) - [`Phalcon\Mvc\Router\Exceptions\EmptyGroupOfRoutes`](#mvcrouterexceptionsemptygroupofroutes) - [`Phalcon\Mvc\Router\Exceptions\GroupRoutesMustBeArray`](#mvcrouterexceptionsgrouproutesmustbearray) - [`Phalcon\Mvc\Router\Exceptions\InvalidCallbackParameter`](#mvcrouterexceptionsinvalidcallbackparameter) - [`Phalcon\Mvc\Router\Exceptions\InvalidConfigSource`](#mvcrouterexceptionsinvalidconfigsource) - [`Phalcon\Mvc\Router\Exceptions\InvalidNotFoundPaths`](#mvcrouterexceptionsinvalidnotfoundpaths) - [`Phalcon\Mvc\Router\Exceptions\InvalidRoutePaths`](#mvcrouterexceptionsinvalidroutepaths) - [`Phalcon\Mvc\Router\Exceptions\InvalidRoutePosition`](#mvcrouterexceptionsinvalidrouteposition) - [`Phalcon\Mvc\Router\Exceptions\InvalidRouterFactoryConfig`](#mvcrouterexceptionsinvalidrouterfactoryconfig) - [`Phalcon\Mvc\Router\Exceptions\MissingGroupRouteKey`](#mvcrouterexceptionsmissinggrouproutekey) - [`Phalcon\Mvc\Router\Exceptions\MissingRouteConfigKey`](#mvcrouterexceptionsmissingrouteconfigkey) - [`Phalcon\Mvc\Router\Exceptions\RequestServiceUnavailable`](#mvcrouterexceptionsrequestserviceunavailable) - [`Phalcon\Mvc\Router\Exceptions\UnknownHttpMethod`](#mvcrouterexceptionsunknownhttpmethod) - [`Phalcon\Mvc\Router\Exceptions\WrongPathsKey`](#mvcrouterexceptionswrongpathskey)
## Mvc\Router\Exceptions\AnnotationsServiceUnavailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/AnnotationsServiceUnavailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\AnnotationsServiceUnavailable`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsannotationsserviceunavailable-__construct }
public function __construct();
## Mvc\Router\Exceptions\BeforeMatchNotCallable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/BeforeMatchNotCallable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\BeforeMatchNotCallable`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsbeforematchnotcallable-__construct }
public function __construct();
## Mvc\Router\Exceptions\ConfigKeyMustBeArray Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/ConfigKeyMustBeArray.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\ConfigKeyMustBeArray`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsconfigkeymustbearray-__construct }
public function __construct( string $key );
## Mvc\Router\Exceptions\EmptyGroupOfRoutes Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/EmptyGroupOfRoutes.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\EmptyGroupOfRoutes`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsemptygroupofroutes-__construct }
public function __construct();
## Mvc\Router\Exceptions\GroupRoutesMustBeArray Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/GroupRoutesMustBeArray.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\GroupRoutesMustBeArray`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsgrouproutesmustbearray-__construct }
public function __construct();
## Mvc\Router\Exceptions\InvalidCallbackParameter Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/InvalidCallbackParameter.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\InvalidCallbackParameter`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsinvalidcallbackparameter-__construct }
public function __construct();
## Mvc\Router\Exceptions\InvalidConfigSource Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/InvalidConfigSource.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\InvalidConfigSource`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsinvalidconfigsource-__construct }
public function __construct();
## Mvc\Router\Exceptions\InvalidNotFoundPaths Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/InvalidNotFoundPaths.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\InvalidNotFoundPaths`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsinvalidnotfoundpaths-__construct }
public function __construct();
## Mvc\Router\Exceptions\InvalidRoutePaths Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/InvalidRoutePaths.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\InvalidRoutePaths`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsinvalidroutepaths-__construct }
public function __construct();
## Mvc\Router\Exceptions\InvalidRoutePosition Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/InvalidRoutePosition.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\InvalidRoutePosition`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsinvalidrouteposition-__construct }
public function __construct();
## Mvc\Router\Exceptions\InvalidRouterFactoryConfig Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/InvalidRouterFactoryConfig.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\InvalidRouterFactoryConfig`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsinvalidrouterfactoryconfig-__construct }
public function __construct();
## Mvc\Router\Exceptions\MissingGroupRouteKey Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/MissingGroupRouteKey.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\MissingGroupRouteKey`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsmissinggrouproutekey-__construct }
public function __construct( string $key );
## Mvc\Router\Exceptions\MissingRouteConfigKey Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/MissingRouteConfigKey.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\MissingRouteConfigKey`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsmissingrouteconfigkey-__construct }
public function __construct( string $key );
## Mvc\Router\Exceptions\RequestServiceUnavailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/RequestServiceUnavailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\RequestServiceUnavailable`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsrequestserviceunavailable-__construct }
public function __construct();
## Mvc\Router\Exceptions\UnknownHttpMethod Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/UnknownHttpMethod.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\UnknownHttpMethod`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionsunknownhttpmethod-__construct }
public function __construct( string $method );
## Mvc\Router\Exceptions\WrongPathsKey Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Exceptions/WrongPathsKey.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Router\Exception`](#mvcrouterexception) - **`Phalcon\Mvc\Router\Exceptions\WrongPathsKey`**
__Uses__ `Phalcon\Mvc\Router\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcrouterexceptionswrongpathskey-__construct }
public function __construct( string $part );
## Mvc\Router\Group Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Group.zep){ .src-btn } Helper class to create a group of routes with common attributes
$router = new \Phalcon\Mvc\Router();

//Create a group with a common module and controller
$blog = new Group(
    [
        "module"     => "blog",
        "controller" => "index",
    ]
);

//All the routes start with /blog
$blog->setPrefix("/blog");

//Add a route to the group
$blog->add(
    "/save",
    [
        "action" => "save",
    ]
);

//Add another route to the group
$blog->add(
    "/edit/{id}",
    [
        "action" => "edit",
    ]
);

//This route maps to a controller different than the default
$blog->add(
    "/blog",
    [
        "controller" => "about",
        "action"     => "index",
    ]
);

//Add the group to the router
$router->mount($blog);
- **`Phalcon\Mvc\Router\Group`** — implements [`Phalcon\Mvc\Router\GroupInterface`](#mvcroutergroupinterface)
### Method Summary
public __construct( mixed $paths = null ) Phalcon\Mvc\Router\Group constructor public RouteInterface add(string $pattern,mixed $paths = null,mixed $httpMethods = null) Adds a route to the router on any HTTP method public RouteInterface addConnect(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is CONNECT public RouteInterface addDelete(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is DELETE public RouteInterface addGet(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is GET public RouteInterface addHead(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is HEAD public RouteInterface addOptions(string $pattern,mixed $paths = null) Add a route to the router that only match if the HTTP method is OPTIONS public RouteInterface addPatch(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is PATCH public RouteInterface addPost(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is POST public RouteInterface addPurge(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is PURGE public RouteInterface addPut(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is PUT public RouteInterface addTrace(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is TRACE public GroupInterface beforeMatch( callable $beforeMatch ) Sets a callback that is called if the route is matched. public void clear() Removes all the pre-defined routes public callable|null getBeforeMatch() Returns the 'before match' callback if any public string|null getHostname() Returns the hostname restriction public array|string|null getPaths() Returns the common paths defined for this group public string|null getPrefix() Returns the common prefix for all the routes public RouteInterface[] getRoutes() Returns the routes added to the group public GroupInterface setHostname( string $hostname ) Set a hostname restriction for all the routes in the group public GroupInterface setPaths( mixed $paths ) Set common paths for all the routes in the group public GroupInterface setPrefix( string $prefix ) Set a common uri prefix for all the routes in this group protected RouteInterface addRoute(string $pattern,mixed $paths = null,mixed $httpMethods = null) Adds a route applying the common attributes
### Properties
protected callable|null $beforeMatch = null
protected string|null $hostname = null
protected array|string|null $paths = null
protected string|null $prefix = null
protected array $routes = []
### Methods
Public · 22
#### `__construct()` { #mvcroutergroup-__construct }
public function __construct( mixed $paths = null );
Phalcon\Mvc\Router\Group constructor #### `add()` { #mvcroutergroup-add }
public function add(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null
): RouteInterface;
Adds a route to the router on any HTTP method
$router->add("/about", "About::index");
#### `addConnect()` { #mvcroutergroup-addconnect }
public function addConnect(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is CONNECT #### `addDelete()` { #mvcroutergroup-adddelete }
public function addDelete(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is DELETE #### `addGet()` { #mvcroutergroup-addget }
public function addGet(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is GET #### `addHead()` { #mvcroutergroup-addhead }
public function addHead(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is HEAD #### `addOptions()` { #mvcroutergroup-addoptions }
public function addOptions(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Add a route to the router that only match if the HTTP method is OPTIONS #### `addPatch()` { #mvcroutergroup-addpatch }
public function addPatch(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PATCH #### `addPost()` { #mvcroutergroup-addpost }
public function addPost(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is POST #### `addPurge()` { #mvcroutergroup-addpurge }
public function addPurge(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PURGE #### `addPut()` { #mvcroutergroup-addput }
public function addPut(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PUT #### `addTrace()` { #mvcroutergroup-addtrace }
public function addTrace(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is TRACE #### `beforeMatch()` { #mvcroutergroup-beforematch }
public function beforeMatch( callable $beforeMatch ): GroupInterface;
Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched #### `clear()` { #mvcroutergroup-clear }
public function clear(): void;
Removes all the pre-defined routes #### `getBeforeMatch()` { #mvcroutergroup-getbeforematch }
public function getBeforeMatch(): callable|null;
Returns the 'before match' callback if any #### `getHostname()` { #mvcroutergroup-gethostname }
public function getHostname(): string|null;
Returns the hostname restriction #### `getPaths()` { #mvcroutergroup-getpaths }
public function getPaths(): array|string|null;
Returns the common paths defined for this group #### `getPrefix()` { #mvcroutergroup-getprefix }
public function getPrefix(): string|null;
Returns the common prefix for all the routes #### `getRoutes()` { #mvcroutergroup-getroutes }
public function getRoutes(): RouteInterface[];
Returns the routes added to the group #### `setHostname()` { #mvcroutergroup-sethostname }
public function setHostname( string $hostname ): GroupInterface;
Set a hostname restriction for all the routes in the group #### `setPaths()` { #mvcroutergroup-setpaths }
public function setPaths( mixed $paths ): GroupInterface;
Set common paths for all the routes in the group #### `setPrefix()` { #mvcroutergroup-setprefix }
public function setPrefix( string $prefix ): GroupInterface;
Set a common uri prefix for all the routes in this group
Protected · 1
#### `addRoute()` { #mvcroutergroup-addroute }
protected function addRoute(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null
): RouteInterface;
Adds a route applying the common attributes ## Mvc\Router\GroupInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/GroupInterface.zep){ .src-btn }
$router = new \Phalcon\Mvc\Router();

// Create a group with a common module and controller
$blog = new Group(
    [
        "module"     => "blog",
        "controller" => "index",
    ]
);

// All the routes start with /blog
$blog->setPrefix("/blog");

// Add a route to the group
$blog->add(
    "/save",
    [
        "action" => "save",
    ]
);

// Add another route to the group
$blog->add(
    "/edit/{id}",
    [
        "action" => "edit",
    ]
);

// This route maps to a controller different than the default
$blog->add(
    "/blog",
    [
        "controller" => "about",
        "action"     => "index",
    ]
);

// Add the group to the router
$router->mount($blog);
- **`Phalcon\Mvc\Router\GroupInterface`**
### Method Summary
public RouteInterface add(string $pattern,mixed $paths = null,mixed $httpMethods = null) Adds a route to the router on any HTTP method public RouteInterface addConnect(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is CONNECT public RouteInterface addDelete(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is DELETE public RouteInterface addGet(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is GET public RouteInterface addHead(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is HEAD public RouteInterface addOptions(string $pattern,mixed $paths = null) Add a route to the router that only match if the HTTP method is OPTIONS public RouteInterface addPatch(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is PATCH public RouteInterface addPost(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is POST public RouteInterface addPurge(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is PURGE public RouteInterface addPut(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is PUT public RouteInterface addTrace(string $pattern,mixed $paths = null) Adds a route to the router that only match if the HTTP method is TRACE public GroupInterface beforeMatch( callable $beforeMatch ) Sets a callback that is called if the route is matched. public void clear() Removes all the pre-defined routes public callable|null getBeforeMatch() Returns the 'before match' callback if any public string|null getHostname() Returns the hostname restriction public array|string|null getPaths() Returns the common paths defined for this group public string|null getPrefix() Returns the common prefix for all the routes public RouteInterface[] getRoutes() Returns the routes added to the group public GroupInterface setHostname( string $hostname ) Set a hostname restriction for all the routes in the group public GroupInterface setPaths( mixed $paths ) Set common paths for all the routes in the group public GroupInterface setPrefix( string $prefix ) Set a common uri prefix for all the routes in this group
### Methods
Public · 21
#### `add()` { #mvcroutergroupinterface-add }
public function add(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null
): RouteInterface;
Adds a route to the router on any HTTP method
router->add("/about", "About::index");
#### `addConnect()` { #mvcroutergroupinterface-addconnect }
public function addConnect(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is CONNECT #### `addDelete()` { #mvcroutergroupinterface-adddelete }
public function addDelete(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is DELETE #### `addGet()` { #mvcroutergroupinterface-addget }
public function addGet(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is GET #### `addHead()` { #mvcroutergroupinterface-addhead }
public function addHead(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is HEAD #### `addOptions()` { #mvcroutergroupinterface-addoptions }
public function addOptions(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Add a route to the router that only match if the HTTP method is OPTIONS #### `addPatch()` { #mvcroutergroupinterface-addpatch }
public function addPatch(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PATCH #### `addPost()` { #mvcroutergroupinterface-addpost }
public function addPost(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is POST #### `addPurge()` { #mvcroutergroupinterface-addpurge }
public function addPurge(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PURGE #### `addPut()` { #mvcroutergroupinterface-addput }
public function addPut(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PUT #### `addTrace()` { #mvcroutergroupinterface-addtrace }
public function addTrace(
    string $pattern,
    mixed $paths = null
): RouteInterface;
Adds a route to the router that only match if the HTTP method is TRACE #### `beforeMatch()` { #mvcroutergroupinterface-beforematch }
public function beforeMatch( callable $beforeMatch ): GroupInterface;
Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched #### `clear()` { #mvcroutergroupinterface-clear }
public function clear(): void;
Removes all the pre-defined routes #### `getBeforeMatch()` { #mvcroutergroupinterface-getbeforematch }
public function getBeforeMatch(): callable|null;
Returns the 'before match' callback if any #### `getHostname()` { #mvcroutergroupinterface-gethostname }
public function getHostname(): string|null;
Returns the hostname restriction #### `getPaths()` { #mvcroutergroupinterface-getpaths }
public function getPaths(): array|string|null;
Returns the common paths defined for this group #### `getPrefix()` { #mvcroutergroupinterface-getprefix }
public function getPrefix(): string|null;
Returns the common prefix for all the routes #### `getRoutes()` { #mvcroutergroupinterface-getroutes }
public function getRoutes(): RouteInterface[];
Returns the routes added to the group #### `setHostname()` { #mvcroutergroupinterface-sethostname }
public function setHostname( string $hostname ): GroupInterface;
Set a hostname restriction for all the routes in the group #### `setPaths()` { #mvcroutergroupinterface-setpaths }
public function setPaths( mixed $paths ): GroupInterface;
Set common paths for all the routes in the group #### `setPrefix()` { #mvcroutergroupinterface-setprefix }
public function setPrefix( string $prefix ): GroupInterface;
Set a common uri prefix for all the routes in this group ## Mvc\Router\Route Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/Route.zep){ .src-btn } This class represents every route added to the router
- **`Phalcon\Mvc\Router\Route`** — implements [`Phalcon\Mvc\Router\RouteInterface`](#mvcrouterrouteinterface)
__Uses__ `Phalcon\Mvc\Router\Exceptions\InvalidRoutePaths` { .api-uses } ### Method Summary
public __construct(string $pattern,mixed $paths = null,mixed $httpMethods = null) Phalcon\Mvc\Router\Route constructor public RouteInterface beforeMatch( callable $callback ) Sets a callback that is called if the route is matched. public string compilePattern( string $pattern ) Replaces placeholders from pattern returning a valid PCRE regular expression public RouteInterface convert(string $name,mixed $converter) {@inheritdoc} public array|bool extractNamedParams( string $pattern ) Extracts parameters from a string public callable|null getBeforeMatch() Returns the 'before match' callback if any public string|null getCompiledHostName() Returns the compiled hostname regex, or null when the hostname is public string getCompiledPattern() Returns the route's compiled pattern public array getConverters() Returns the router converter public GroupInterface|null getGroup() Returns the group associated with the route public string|null getHostname() Returns the hostname restriction if any public array|string|null getHttpMethods() Returns the HTTP methods that constraint matching the route public callable|null getMatch() Returns the 'match' callback if any public string|null getName() Returns the route's name public array getPaths() Returns the paths public string getPattern() Returns the route's pattern public array getReversedPaths() Returns the paths using positions as keys and names as values public string getRouteId() Returns the route's id public array getRoutePaths( mixed $paths = null ) Returns routePaths public RouteInterface match( mixed $callback ) Allows to set a callback to handle the request directly in the route public void reConfigure(string $pattern,mixed $paths = null) Reconfigure the route adding a new pattern and a set of paths public void reset() Resets the internal route id generator public RouteInterface setGroup( GroupInterface $group ) Sets the group associated with the route public RouteInterface setHostname( string $hostname ) Sets a hostname restriction to the route public RouteInterface setHttpMethods( mixed $httpMethods ) Sets a set of HTTP methods that constraint the matching of the route (alias of via) public RouteInterface setName( string $name ) Sets the route's name public RouteInterface setRouteId( string $routeId ) Sets the route's id. Intended for restoring cached routes - most public RouteInterface via( mixed $httpMethods ) Set one or more HTTP methods that constraint the matching of the route
### Properties
protected callable|null $beforeMatch = null
protected string|null|false $compiledHostName = false Cached compiled hostname regex. false means "not yet computed"; null means "hostname is literal - use string equality"; any string means "use this as the PCRE pattern."
protected string|null $compiledPattern = null
protected array $converters = []
protected GroupInterface|null $group = null
protected string|null $hostname = null
protected callable|null $match = null
protected array|string|null $methods = []
protected string|null $name = null
protected array $paths = []
protected string $pattern
protected string $routeId = ""
protected int $uniqueId = 0
### Methods
Public · 28
#### `__construct()` { #mvcrouterroute-__construct }
public function __construct(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null
);
Phalcon\Mvc\Router\Route constructor #### `beforeMatch()` { #mvcrouterroute-beforematch }
public function beforeMatch( callable $callback ): RouteInterface;
Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched
$router->add(
    "/login",
    [
        "module"     => "admin",
        "controller" => "session",
    ]
)->beforeMatch(
    function ($uri, $route) {
        // Check if the request was made with Ajax
        if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") {
            return false;
        }

        return true;
    }
);
#### `compilePattern()` { #mvcrouterroute-compilepattern }
public function compilePattern( string $pattern ): string;
Replaces placeholders from pattern returning a valid PCRE regular expression #### `convert()` { #mvcrouterroute-convert }
public function convert(
    string $name,
    mixed $converter
): RouteInterface;
{@inheritdoc} #### `extractNamedParams()` { #mvcrouterroute-extractnamedparams }
public function extractNamedParams( string $pattern ): array|bool;
Extracts parameters from a string #### `getBeforeMatch()` { #mvcrouterroute-getbeforematch }
public function getBeforeMatch(): callable|null;
Returns the 'before match' callback if any #### `getCompiledHostName()` { #mvcrouterroute-getcompiledhostname }
public function getCompiledHostName(): string|null;
Returns the compiled hostname regex, or null when the hostname is literal and a string-equality comparison should be used. The result is cached after first computation; setHostname() clears the cache. #### `getCompiledPattern()` { #mvcrouterroute-getcompiledpattern }
public function getCompiledPattern(): string;
Returns the route's compiled pattern #### `getConverters()` { #mvcrouterroute-getconverters }
public function getConverters(): array;
Returns the router converter #### `getGroup()` { #mvcrouterroute-getgroup }
public function getGroup(): GroupInterface|null;
Returns the group associated with the route #### `getHostname()` { #mvcrouterroute-gethostname }
public function getHostname(): string|null;
Returns the hostname restriction if any #### `getHttpMethods()` { #mvcrouterroute-gethttpmethods }
public function getHttpMethods(): array|string|null;
Returns the HTTP methods that constraint matching the route #### `getMatch()` { #mvcrouterroute-getmatch }
public function getMatch(): callable|null;
Returns the 'match' callback if any #### `getName()` { #mvcrouterroute-getname }
public function getName(): string|null;
Returns the route's name #### `getPaths()` { #mvcrouterroute-getpaths }
public function getPaths(): array;
Returns the paths #### `getPattern()` { #mvcrouterroute-getpattern }
public function getPattern(): string;
Returns the route's pattern #### `getReversedPaths()` { #mvcrouterroute-getreversedpaths }
public function getReversedPaths(): array;
Returns the paths using positions as keys and names as values #### `getRouteId()` { #mvcrouterroute-getrouteid }
public function getRouteId(): string;
Returns the route's id #### `getRoutePaths()` { #mvcrouterroute-getroutepaths }
public static function getRoutePaths( mixed $paths = null ): array;
Returns routePaths #### `match()` { #mvcrouterroute-match }
public function match( mixed $callback ): RouteInterface;
Allows to set a callback to handle the request directly in the route
$router->add(
    "/help",
    []
)->match(
    function () {
        return $this->getResponse()->redirect("https://support.google.com/", true);
    }
);
#### `reConfigure()` { #mvcrouterroute-reconfigure }
public function reConfigure(
    string $pattern,
    mixed $paths = null
): void;
Reconfigure the route adding a new pattern and a set of paths #### `reset()` { #mvcrouterroute-reset }
public static function reset(): void;
Resets the internal route id generator #### `setGroup()` { #mvcrouterroute-setgroup }
public function setGroup( GroupInterface $group ): RouteInterface;
Sets the group associated with the route #### `setHostname()` { #mvcrouterroute-sethostname }
public function setHostname( string $hostname ): RouteInterface;
Sets a hostname restriction to the route
$route->setHostname("localhost");
#### `setHttpMethods()` { #mvcrouterroute-sethttpmethods }
public function setHttpMethods( mixed $httpMethods ): RouteInterface;
Sets a set of HTTP methods that constraint the matching of the route (alias of via)
$route->setHttpMethods("GET");

$route->setHttpMethods(
    [
        "GET",
        "POST",
    ]
);
#### `setName()` { #mvcrouterroute-setname }
public function setName( string $name ): RouteInterface;
Sets the route's name
$router->add(
    "/about",
    [
        "controller" => "about",
    ]
)->setName("about");
#### `setRouteId()` { #mvcrouterroute-setrouteid }
public function setRouteId( string $routeId ): RouteInterface;
Sets the route's id. Intended for restoring cached routes - most applications should rely on the auto-incrementing id assigned by the constructor. #### `via()` { #mvcrouterroute-via }
public function via( mixed $httpMethods ): RouteInterface;
Set one or more HTTP methods that constraint the matching of the route
$route->via("GET");

$route->via(
    [
        "GET",
        "POST",
    ]
);
## Mvc\Router\RouteInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/RouteInterface.zep){ .src-btn } Interface for Phalcon\Mvc\Router\Route
- **`Phalcon\Mvc\Router\RouteInterface`**
### Method Summary
public string compilePattern( string $pattern ) Replaces placeholders from pattern returning a valid PCRE regular expression public RouteInterface convert(string $name,mixed $converter) Adds a converter to perform an additional transformation for certain parameter. public string getCompiledPattern() Returns the route's pattern public string|null getHostname() Returns the hostname restriction if any public array|string|null getHttpMethods() Returns the HTTP methods that constraint matching the route public string|null getName() Returns the route's name public array getPaths() Returns the paths public string getPattern() Returns the route's pattern public array getReversedPaths() Returns the paths using positions as keys and names as values public string getRouteId() Returns the route's id public void reConfigure(string $pattern,mixed $paths = null) Reconfigure the route adding a new pattern and a set of paths public void reset() Resets the internal route id generator public RouteInterface setHostname( string $hostname ) Sets a hostname restriction to the route public RouteInterface setHttpMethods( mixed $httpMethods ) Sets a set of HTTP methods that constraint the matching of the route public RouteInterface setName( string $name ) Sets the route's name public RouteInterface setRouteId( string $routeId ) Sets the route's id (intended for restoring cached routes) public RouteInterface via( mixed $httpMethods ) Set one or more HTTP methods that constraint the matching of the route
### Methods
Public · 17
#### `compilePattern()` { #mvcrouterrouteinterface-compilepattern }
public function compilePattern( string $pattern ): string;
Replaces placeholders from pattern returning a valid PCRE regular expression #### `convert()` { #mvcrouterrouteinterface-convert }
public function convert(
    string $name,
    mixed $converter
): RouteInterface;
Adds a converter to perform an additional transformation for certain parameter. #### `getCompiledPattern()` { #mvcrouterrouteinterface-getcompiledpattern }
public function getCompiledPattern(): string;
Returns the route's pattern #### `getHostname()` { #mvcrouterrouteinterface-gethostname }
public function getHostname(): string|null;
Returns the hostname restriction if any #### `getHttpMethods()` { #mvcrouterrouteinterface-gethttpmethods }
public function getHttpMethods(): array|string|null;
Returns the HTTP methods that constraint matching the route #### `getName()` { #mvcrouterrouteinterface-getname }
public function getName(): string|null;
Returns the route's name #### `getPaths()` { #mvcrouterrouteinterface-getpaths }
public function getPaths(): array;
Returns the paths #### `getPattern()` { #mvcrouterrouteinterface-getpattern }
public function getPattern(): string;
Returns the route's pattern #### `getReversedPaths()` { #mvcrouterrouteinterface-getreversedpaths }
public function getReversedPaths(): array;
Returns the paths using positions as keys and names as values #### `getRouteId()` { #mvcrouterrouteinterface-getrouteid }
public function getRouteId(): string;
Returns the route's id #### `reConfigure()` { #mvcrouterrouteinterface-reconfigure }
public function reConfigure(
    string $pattern,
    mixed $paths = null
): void;
Reconfigure the route adding a new pattern and a set of paths #### `reset()` { #mvcrouterrouteinterface-reset }
public static function reset(): void;
Resets the internal route id generator #### `setHostname()` { #mvcrouterrouteinterface-sethostname }
public function setHostname( string $hostname ): RouteInterface;
Sets a hostname restriction to the route #### `setHttpMethods()` { #mvcrouterrouteinterface-sethttpmethods }
public function setHttpMethods( mixed $httpMethods ): RouteInterface;
Sets a set of HTTP methods that constraint the matching of the route #### `setName()` { #mvcrouterrouteinterface-setname }
public function setName( string $name ): RouteInterface;
Sets the route's name #### `setRouteId()` { #mvcrouterrouteinterface-setrouteid }
public function setRouteId( string $routeId ): RouteInterface;
Sets the route's id (intended for restoring cached routes) #### `via()` { #mvcrouterrouteinterface-via }
public function via( mixed $httpMethods ): RouteInterface;
Set one or more HTTP methods that constraint the matching of the route ## Mvc\Router\RouterFactory Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Router/RouterFactory.zep){ .src-btn } Phalcon\Mvc\Router\RouterFactory Builds a Router from an array or ConfigInterface and loads routes via Router::loadFromConfig.
use Phalcon\Mvc\Router\RouterFactory;

$router = (new RouterFactory())->load(
    [
        "defaultRoutes" : false,
        "routes" : [
            ["method" : "get", "pattern" : "/users", "paths" : "Users::index"]
        ]
    ]
);
- **`Phalcon\Mvc\Router\RouterFactory`**
__Uses__ `Phalcon\Config\ConfigInterface` · `Phalcon\Mvc\Router` · `Phalcon\Mvc\RouterInterface` · `Phalcon\Mvc\Router\Exceptions\InvalidRouterFactoryConfig` { .api-uses } ### Method Summary ### Methods
Public · 2
#### `load()` { #mvcrouterrouterfactory-load }
public function load( mixed $config ): RouterInterface;
Builds a Router from a config array or ConfigInterface and loads routes. #### `newInstance()` { #mvcrouterrouterfactory-newinstance }
public function newInstance( bool $defaultRoutes = true ): RouterInterface;
Returns a bare Router instance. ## Mvc\Url Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Url.zep){ .src-btn } This component helps in the generation of: URIs, URLs and Paths
// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");

// Generate a URL for a predefined route
echo $url->get(
    [
        "for"   => "blog-post",
        "title" => "some-cool-stuff",
        "year"  => "2012",
    ]
);
- `stdClass` - [`Phalcon\Di\AbstractInjectionAware`](phalcon_di.md#diabstractinjectionaware) - **`Phalcon\Mvc\Url`** — implements [`Phalcon\Mvc\Url\UrlInterface`](#mvcurlurlinterface)
__Uses__ `Phalcon\Di\AbstractInjectionAware` · `Phalcon\Di\DiInterface` · `Phalcon\Mvc\RouterInterface` · `Phalcon\Mvc\Router\RouteInterface` · `Phalcon\Mvc\Url\Exception` · `Phalcon\Mvc\Url\Exceptions\MissingRouteName` · `Phalcon\Mvc\Url\Exceptions\RouteNotFound` · `Phalcon\Mvc\Url\Exceptions\RouterServiceUnavailable` · `Phalcon\Mvc\Url\UrlInterface` { .api-uses } ### Method Summary ### Properties
protected null | string $basePath = null
protected null | string $baseUri = null
protected RouterInterface | null $router = null
protected null | string $staticBaseUri = null
### Methods
Public · 10
#### `__construct()` { #mvcurl-__construct }
public function __construct( RouterInterface $router = null );
#### `get()` { #mvcurl-get }
public function get(
    mixed $uri = null,
    mixed $arguments = null,
    bool $local = null,
    mixed $baseUri = null,
    bool $replaceArgs = false
): string;
Generates a URL
// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");

// Generate a URL for a predefined route
echo $url->get(
    [
        "for"   => "blog-post",
        "title" => "some-cool-stuff",
        "year"  => "2015",
    ]
);

// Generate a URL with GET arguments (/show/products?id=1&name=Carrots)
echo $url->get(
    "show/products",
    [
        "id"   => 1,
        "name" => "Carrots",
    ]
);

// Generate an absolute URL by setting the third parameter as false.
echo $url->get(
    "https://phalcon.io/",
    null,
    false
);

// Override existing query string keys instead of appending duplicates.
// Without the fifth argument: "http://example.com?page=1&page=5".
// With it set to true:        "http://example.com?page=5".
echo $url->get(
    "http://example.com?page=1",
    ["page" => 5],
    null,
    null,
    true
);
#### `getBasePath()` { #mvcurl-getbasepath }
public function getBasePath(): string|null;
Returns the base path #### `getBaseUri()` { #mvcurl-getbaseuri }
public function getBaseUri(): string;
Returns the prefix for all the generated urls. By default / #### `getStatic()` { #mvcurl-getstatic }
public function getStatic( mixed $uri = null ): string;
Generates a URL for a static resource
// Generate a URL for a static resource
echo $url->getStatic("img/logo.png");

// Generate a URL for a static predefined route
echo $url->getStatic(
    [
        "for" => "logo-cdn",
    ]
);
#### `getStaticBaseUri()` { #mvcurl-getstaticbaseuri }
public function getStaticBaseUri(): string;
Returns the prefix for all the generated static urls. By default / #### `path()` { #mvcurl-path }
public function path( string $path = null ): string;
Generates a local path #### `setBasePath()` { #mvcurl-setbasepath }
public function setBasePath( string $basePath ): UrlInterface;
Sets a base path for all the generated paths
$url->setBasePath("/var/www/htdocs/");
#### `setBaseUri()` { #mvcurl-setbaseuri }
public function setBaseUri( string $baseUri ): UrlInterface;
Sets a prefix for all the URIs to be generated
$url->setBaseUri("/invo/");

$url->setBaseUri("/invo/index.php/");
#### `setStaticBaseUri()` { #mvcurl-setstaticbaseuri }
public function setStaticBaseUri( string $staticBaseUri ): UrlInterface;
Sets a prefix for all static URLs generated
$url->setStaticBaseUri("/invo/");
## Mvc\Url\Exception Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Url/Exception.zep){ .src-btn } Phalcon\Mvc\Url\Exception Exceptions thrown in Phalcon\Mvc\Url will use this class
- `\Exception` - **`Phalcon\Mvc\Url\Exception`** - [`Phalcon\Mvc\Url\Exceptions\MissingRouteName`](#mvcurlexceptionsmissingroutename) - [`Phalcon\Mvc\Url\Exceptions\RouteNotFound`](#mvcurlexceptionsroutenotfound) - [`Phalcon\Mvc\Url\Exceptions\RouterServiceUnavailable`](#mvcurlexceptionsrouterserviceunavailable)
## Mvc\Url\Exceptions\MissingRouteName Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Url/Exceptions/MissingRouteName.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Url\Exception`](#mvcurlexception) - **`Phalcon\Mvc\Url\Exceptions\MissingRouteName`**
__Uses__ `Phalcon\Mvc\Url\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcurlexceptionsmissingroutename-__construct }
public function __construct();
## Mvc\Url\Exceptions\RouteNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Url/Exceptions/RouteNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Url\Exception`](#mvcurlexception) - **`Phalcon\Mvc\Url\Exceptions\RouteNotFound`**
__Uses__ `Phalcon\Mvc\Url\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcurlexceptionsroutenotfound-__construct }
public function __construct( string $name );
## Mvc\Url\Exceptions\RouterServiceUnavailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Url/Exceptions/RouterServiceUnavailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\Url\Exception`](#mvcurlexception) - **`Phalcon\Mvc\Url\Exceptions\RouterServiceUnavailable`**
__Uses__ `Phalcon\Mvc\Url\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcurlexceptionsrouterserviceunavailable-__construct }
public function __construct();
## Mvc\Url\UrlInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/Url/UrlInterface.zep){ .src-btn } Interface for Phalcon\Mvc\Url\UrlInterface
- **`Phalcon\Mvc\Url\UrlInterface`**
### Method Summary ### Methods
Public · 6
#### `get()` { #mvcurlurlinterface-get }
public function get(
    mixed $uri = null,
    mixed $arguments = null,
    bool $local = null,
    mixed $baseUri = null,
    bool $replaceArgs = false
): string;
Generates a URL #### `getBasePath()` { #mvcurlurlinterface-getbasepath }
public function getBasePath(): string|null;
Returns a base path #### `getBaseUri()` { #mvcurlurlinterface-getbaseuri }
public function getBaseUri(): string;
Returns the prefix for all the generated urls. By default / #### `path()` { #mvcurlurlinterface-path }
public function path( string $path = null ): string;
Generates a local path #### `setBasePath()` { #mvcurlurlinterface-setbasepath }
public function setBasePath( string $basePath ): UrlInterface;
Sets a base paths for all the generated paths #### `setBaseUri()` { #mvcurlurlinterface-setbaseuri }
public function setBaseUri( string $baseUri ): UrlInterface;
Sets a prefix to all the urls generated ## Mvc\View Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View.zep){ .src-btn } Phalcon\Mvc\View is a class for working with the "view" portion of the model-view-controller pattern. That is, it exists to help keep the view script separate from the model and controller scripts. It provides a system of helpers, output filters, and variable escaping.
use Phalcon\Mvc\View;

$view = new View();

// Setting views directory
$view->setViewsDir("app/views/");

$view->start();

// Shows recent posts view (app/views/posts/recent.phtml)
$view->render("posts", "recent");
$view->finish();

// Printing views output
echo $view->getContent();
- `stdClass` - [`Phalcon\Di\Injectable`](phalcon_di.md#diinjectable) - **`Phalcon\Mvc\View`** — implements [`Phalcon\Mvc\ViewInterface`](#mvcviewinterface), [`Phalcon\Events\EventsAwareInterface`](phalcon_events.md#eventseventsawareinterface)
__Uses__ `Closure` · `Phalcon\Di\DiInterface` · `Phalcon\Di\Injectable` · `Phalcon\Events\EventsAwareInterface` · `Phalcon\Events\ManagerInterface` · `Phalcon\Mvc\View\Engine\Php` · `Phalcon\Mvc\View\Exception` · `Phalcon\Mvc\View\Exceptions\InvalidEngineRegistration` · `Phalcon\Mvc\View\Exceptions\InvalidViewsDirType` · `Phalcon\Mvc\View\Exceptions\ViewNotFound` · `Phalcon\Mvc\View\Exceptions\ViewServicesUnavailable` · `Phalcon\Mvc\View\Exceptions\ViewsDirItemMustBeString` { .api-uses } ### Method Summary
public __construct( array $options = [] ) Phalcon\Mvc\View constructor public mixed|null __get( string $key ) Magic method to retrieve a variable passed to the view public bool __isset( string $key ) Magic method to retrieve if a variable is set in the view public __set(string $key,mixed $value) Magic method to pass variables to the views public static cleanTemplateAfter() Resets any template before layouts public static cleanTemplateBefore() Resets any "template before" layouts public static disable() Disables the auto-rendering process public static disableLevel( mixed $level ) Disables a specific level of rendering public static enable() Enables the auto-rendering process public bool exists( string $view ) Checks whether view exists public static finish() Finishes the render process by stopping the output buffering public string getActionName() Gets the name of the action rendered public string|array getActiveRenderPath() Returns the path (or paths) of the views that are currently rendered public string getBasePath() Gets base path public string getContent() Returns output from another view stage public string getControllerName() Gets the name of the controller rendered public int getCurrentRenderLevel() public ManagerInterface|null getEventsManager() Returns the internal event manager public string|null getLayout() Returns the name of the main view public string getLayoutsDir() Gets the current layouts sub-directory public string getMainView() Returns the name of the main view public array getParamsToView() Returns parameters to views public string getPartial(string $partialPath,mixed $params = null) Renders a partial view public string getPartialsDir() Gets the current partials sub-directory public array getRegisteredEngines() public string getRender(string $controllerName,string $actionName,array $params = [],mixed $configCallback = null) Perform the automatic rendering returning the output as a string public int getRenderLevel() public mixed|null getVar( string $key ) Returns a parameter previously set in the view public string|array getViewsDir() Gets views directory public bool has( string $view ) Checks whether view exists public bool isDisabled() Whether automatic rendering is enabled public partial(string $partialPath,mixed $params = null) Renders a partial view public static pick( mixed $renderView ) Choose a different view to render instead of last-controller/last-action public bool processRender(string $controllerName,string $actionName,array $params = [],bool $fireEvents = true) Processes the view and templates; Fires events if needed public static registerEngines( array $engines ) Register templating engines public static|false render(string $controllerName,string $actionName,array $params = []) Executes render process from dispatching data public static reset() Resets the view component to its factory default values public static setBasePath( string $basePath ) Sets base path. Depending of your platform, always add a trailing slash public static setContent( string $content ) Externally sets the view content public void setEventsManager( ManagerInterface $eventsManager ) Sets the events manager public static setLayout( string $layout ) Change the layout to be used instead of using the name of the latest public static setLayoutsDir( string $layoutsDir ) Sets the layouts sub-directory. Must be a directory under the views public static setMainView( string $viewPath ) Sets default view name. Must be a file without extension in the views public static setParamToView(string $key,mixed $value) Adds parameters to views (alias of setVar) public static setPartialsDir( string $partialsDir ) Sets a partials sub-directory. Must be a directory under the views public static setRenderLevel( int $level ) Sets the render level for the view public static setTemplateAfter( mixed $templateAfter ) Sets a "template after" controller layout public static setTemplateBefore( mixed $templateBefore ) Sets a template before the controller layout public static setVar(string $key,mixed $value) Set a single view parameter public static setVars(array $params,bool $merge = true) Set all the render params public static setViewsDir( mixed $viewsDir ) Sets the views directory. Depending of your platform, public static start() Starts rendering process enabling the output buffering public string toString(string $controllerName,string $actionName,array $params = []) Renders the view and returns it as a string protected engineRender(array $engines,string $viewPath,bool $silence,bool $mustClean = true) Checks whether view exists on registered extensions and render it protected array getViewsDirs() Gets views directories protected isAbsolutePath( string $path ) Checks if a path is absolute or not protected array loadTemplateEngines() Loads registered template engines, if none is registered it will use
### Constants
int LEVEL_ACTION_VIEW = 1 Render Level: To the action view
int LEVEL_AFTER_TEMPLATE = 4 Render Level: Render to the templates "after"
int LEVEL_BEFORE_TEMPLATE = 2 Render Level: To the templates "before"
int LEVEL_LAYOUT = 3 Render Level: To the controller layout
int LEVEL_MAIN_LAYOUT = 5 Render Level: To the main layout
int LEVEL_NO_RENDER = 0 Render Level: No render any view
### Properties
protected string $actionName
protected array $activeRenderPaths
protected string $basePath = ""
protected string $content = ""
protected string $controllerName
protected int $currentRenderLevel = 0
protected bool $disabled = false
protected array $disabledLevels = []
protected array|bool $engines = false
protected ManagerInterface|null $eventsManager
protected string|null $layout = null
protected string $layoutsDir = ""
protected string $mainView = "index"
protected array $options = []
protected array $params = []
protected string $partialsDir = ""
protected array|null $pickView
protected array $registeredEngines = []
protected int $renderLevel = 5
protected array $templatesAfter = []
protected array $templatesBefore = []
protected array $viewParams = []
protected array $viewsDirs = []
### Methods
Public · 53
#### `__construct()` { #mvcview-__construct }
public function __construct( array $options = [] );
Phalcon\Mvc\View constructor #### `__get()` { #mvcview-__get }
public function __get( string $key ): mixed|null;
Magic method to retrieve a variable passed to the view
echo $this->view->products;
#### `__isset()` { #mvcview-__isset }
public function __isset( string $key ): bool;
Magic method to retrieve if a variable is set in the view
echo isset($this->view->products);
#### `__set()` { #mvcview-__set }
public function __set(
    string $key,
    mixed $value
);
Magic method to pass variables to the views
$this->view->products = $products;
#### `cleanTemplateAfter()` { #mvcview-cleantemplateafter }
public function cleanTemplateAfter(): static;
Resets any template before layouts #### `cleanTemplateBefore()` { #mvcview-cleantemplatebefore }
public function cleanTemplateBefore(): static;
Resets any "template before" layouts #### `disable()` { #mvcview-disable }
public function disable(): static;
Disables the auto-rendering process #### `disableLevel()` { #mvcview-disablelevel }
public function disableLevel( mixed $level ): static;
Disables a specific level of rendering
// Render all levels except ACTION level
$this->view->disableLevel(
    View::LEVEL_ACTION_VIEW
);
#### `enable()` { #mvcview-enable }
public function enable(): static;
Enables the auto-rendering process #### `exists()` { #mvcview-exists }
public function exists( string $view ): bool;
Checks whether view exists #### `finish()` { #mvcview-finish }
public function finish(): static;
Finishes the render process by stopping the output buffering #### `getActionName()` { #mvcview-getactionname }
public function getActionName(): string;
Gets the name of the action rendered #### `getActiveRenderPath()` { #mvcview-getactiverenderpath }
public function getActiveRenderPath(): string|array;
Returns the path (or paths) of the views that are currently rendered #### `getBasePath()` { #mvcview-getbasepath }
public function getBasePath(): string;
Gets base path #### `getContent()` { #mvcview-getcontent }
public function getContent(): string;
Returns output from another view stage #### `getControllerName()` { #mvcview-getcontrollername }
public function getControllerName(): string;
Gets the name of the controller rendered #### `getCurrentRenderLevel()` { #mvcview-getcurrentrenderlevel }
public function getCurrentRenderLevel(): int;
#### `getEventsManager()` { #mvcview-geteventsmanager }
public function getEventsManager(): ManagerInterface|null;
Returns the internal event manager #### `getLayout()` { #mvcview-getlayout }
public function getLayout(): string|null;
Returns the name of the main view #### `getLayoutsDir()` { #mvcview-getlayoutsdir }
public function getLayoutsDir(): string;
Gets the current layouts sub-directory #### `getMainView()` { #mvcview-getmainview }
public function getMainView(): string;
Returns the name of the main view #### `getParamsToView()` { #mvcview-getparamstoview }
public function getParamsToView(): array;
Returns parameters to views #### `getPartial()` { #mvcview-getpartial }
public function getPartial(
    string $partialPath,
    mixed $params = null
): string;
Renders a partial view
// Retrieve the contents of a partial
echo $this->getPartial("shared/footer");
// Retrieve the contents of a partial with arguments
echo $this->getPartial(
    "shared/footer",
    [
        "content" => $html,
    ]
);
#### `getPartialsDir()` { #mvcview-getpartialsdir }
public function getPartialsDir(): string;
Gets the current partials sub-directory #### `getRegisteredEngines()` { #mvcview-getregisteredengines }
public function getRegisteredEngines(): array;
#### `getRender()` { #mvcview-getrender }
public function getRender(
    string $controllerName,
    string $actionName,
    array $params = [],
    mixed $configCallback = null
): string;
Perform the automatic rendering returning the output as a string
$template = $this->view->getRender(
    "products",
    "show",
    [
        "products" => $products,
    ]
);
#### `getRenderLevel()` { #mvcview-getrenderlevel }
public function getRenderLevel(): int;
#### `getVar()` { #mvcview-getvar }
public function getVar( string $key ): mixed|null;
Returns a parameter previously set in the view #### `getViewsDir()` { #mvcview-getviewsdir }
public function getViewsDir(): string|array;
Gets views directory #### `has()` { #mvcview-has }
public function has( string $view ): bool;
Checks whether view exists #### `isDisabled()` { #mvcview-isdisabled }
public function isDisabled(): bool;
Whether automatic rendering is enabled #### `partial()` { #mvcview-partial }
public function partial(
    string $partialPath,
    mixed $params = null
);
Renders a partial view
// Show a partial inside another view
$this->partial("shared/footer");
// Show a partial inside another view with parameters
$this->partial(
    "shared/footer",
    [
        "content" => $html,
    ]
);
#### `pick()` { #mvcview-pick }
public function pick( mixed $renderView ): static;
Choose a different view to render instead of last-controller/last-action
use Phalcon\Mvc\Controller;

class ProductsController extends Controller
{
    public function saveAction()
    {
        // Do some save stuff...

        // Then show the list view
        $this->view->pick("products/list");
    }
}
#### `processRender()` { #mvcview-processrender }
public function processRender(
    string $controllerName,
    string $actionName,
    array $params = [],
    bool $fireEvents = true
): bool;
Processes the view and templates; Fires events if needed #### `registerEngines()` { #mvcview-registerengines }
public function registerEngines( array $engines ): static;
Register templating engines
$this->view->registerEngines(
    [
        ".phtml" => \Phalcon\Mvc\View\Engine\Php::class,
        ".volt"  => \Phalcon\Mvc\View\Engine\Volt::class,
        ".mhtml" => \MyCustomEngine::class,
    ]
);
#### `render()` { #mvcview-render }
public function render(
    string $controllerName,
    string $actionName,
    array $params = []
): static|false;
Executes render process from dispatching data
// Shows recent posts view (app/views/posts/recent.phtml)
$view->start()->render("posts", "recent")->finish();
#### `reset()` { #mvcview-reset }
public function reset(): static;
Resets the view component to its factory default values #### `setBasePath()` { #mvcview-setbasepath }
public function setBasePath( string $basePath ): static;
Sets base path. Depending of your platform, always add a trailing slash or backslash
$view->setBasePath(__DIR__ . "/");
#### `setContent()` { #mvcview-setcontent }
public function setContent( string $content ): static;
Externally sets the view content
$this->view->setContent("<h1>hello</h1>");
#### `setEventsManager()` { #mvcview-seteventsmanager }
public function setEventsManager( ManagerInterface $eventsManager ): void;
Sets the events manager #### `setLayout()` { #mvcview-setlayout }
public function setLayout( string $layout ): static;
Change the layout to be used instead of using the name of the latest controller name
$this->view->setLayout("main");
#### `setLayoutsDir()` { #mvcview-setlayoutsdir }
public function setLayoutsDir( string $layoutsDir ): static;
Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash
$view->setLayoutsDir("../common/layouts/");
#### `setMainView()` { #mvcview-setmainview }
public function setMainView( string $viewPath ): static;
Sets default view name. Must be a file without extension in the views directory
// Renders as main view views-dir/base.phtml
$this->view->setMainView("base");
#### `setParamToView()` { #mvcview-setparamtoview }
public function setParamToView(
    string $key,
    mixed $value
): static;
Adds parameters to views (alias of setVar)
$this->view->setParamToView("products", $products);
#### `setPartialsDir()` { #mvcview-setpartialsdir }
public function setPartialsDir( string $partialsDir ): static;
Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash
$view->setPartialsDir("../common/partials/");
#### `setRenderLevel()` { #mvcview-setrenderlevel }
public function setRenderLevel( int $level ): static;
Sets the render level for the view
// Render the view related to the controller only
$this->view->setRenderLevel(
    View::LEVEL_LAYOUT
);
#### `setTemplateAfter()` { #mvcview-settemplateafter }
public function setTemplateAfter( mixed $templateAfter ): static;
Sets a "template after" controller layout #### `setTemplateBefore()` { #mvcview-settemplatebefore }
public function setTemplateBefore( mixed $templateBefore ): static;
Sets a template before the controller layout #### `setVar()` { #mvcview-setvar }
public function setVar(
    string $key,
    mixed $value
): static;
Set a single view parameter
$this->view->setVar("products", $products);
#### `setVars()` { #mvcview-setvars }
public function setVars(
    array $params,
    bool $merge = true
): static;
Set all the render params
$this->view->setVars(
    [
        "products" => $products,
    ]
);
#### `setViewsDir()` { #mvcview-setviewsdir }
public function setViewsDir( mixed $viewsDir ): static;
Sets the views directory. Depending of your platform, always add a trailing slash or backslash #### `start()` { #mvcview-start }
public function start(): static;
Starts rendering process enabling the output buffering #### `toString()` { #mvcview-tostring }
public function toString(
    string $controllerName,
    string $actionName,
    array $params = []
): string;
Renders the view and returns it as a string
Protected · 4
#### `engineRender()` { #mvcview-enginerender }
protected function engineRender(
    array $engines,
    string $viewPath,
    bool $silence,
    bool $mustClean = true
);
Checks whether view exists on registered extensions and render it #### `getViewsDirs()` { #mvcview-getviewsdirs }
protected function getViewsDirs(): array;
Gets views directories #### `isAbsolutePath()` { #mvcview-isabsolutepath }
final protected function isAbsolutePath( string $path );
Checks if a path is absolute or not #### `loadTemplateEngines()` { #mvcview-loadtemplateengines }
protected function loadTemplateEngines(): array;
Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php ## Mvc\ViewBaseInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/ViewBaseInterface.zep){ .src-btn } Interface for Phalcon\Mvc\View and Phalcon\Mvc\View\Simple
- **`Phalcon\Mvc\ViewBaseInterface`** - [`Phalcon\Mvc\ViewInterface`](#mvcviewinterface)
__Uses__ `Phalcon\Cache\Adapter\AdapterInterface` { .api-uses } ### Method Summary ### Methods
Public · 8
#### `getContent()` { #mvcviewbaseinterface-getcontent }
public function getContent(): string;
Returns cached output from another view stage #### `getParamsToView()` { #mvcviewbaseinterface-getparamstoview }
public function getParamsToView(): array;
Returns parameters to views #### `getViewsDir()` { #mvcviewbaseinterface-getviewsdir }
public function getViewsDir(): string|array;
Gets views directory #### `partial()` { #mvcviewbaseinterface-partial }
public function partial(
    string $partialPath,
    mixed $params = null
);
Renders a partial view #### `setContent()` { #mvcviewbaseinterface-setcontent }
public function setContent( string $content );
Externally sets the view content #### `setParamToView()` { #mvcviewbaseinterface-setparamtoview }
public function setParamToView(
    string $key,
    mixed $value
);
Adds parameters to views (alias of setVar) #### `setVar()` { #mvcviewbaseinterface-setvar }
public function setVar(
    string $key,
    mixed $value
);
Adds parameters to views #### `setViewsDir()` { #mvcviewbaseinterface-setviewsdir }
public function setViewsDir( string $viewsDir );
Sets views directory. Depending of your platform, always add a trailing slash or backslash ## Mvc\ViewInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/ViewInterface.zep){ .src-btn } Interface for Phalcon\Mvc\View
- [`Phalcon\Mvc\ViewBaseInterface`](#mvcviewbaseinterface) - **`Phalcon\Mvc\ViewInterface`**
### Method Summary
public cleanTemplateAfter() Resets any template before layouts public cleanTemplateBefore() Resets any template before layouts public disable() Disables the auto-rendering process public enable() Enables the auto-rendering process public finish() Finishes the render process by stopping the output buffering public string getActionName() Gets the name of the action rendered public string|array getActiveRenderPath() Returns the path of the view that is currently rendered public string getBasePath() Gets base path public string getControllerName() Gets the name of the controller rendered public string|null getLayout() Returns the name of the main view public string getLayoutsDir() Gets the current layouts sub-directory public string getMainView() Returns the name of the main view public string getPartialsDir() Gets the current partials sub-directory public bool isDisabled() Whether the automatic rendering is disabled public pick( string $renderView ) Choose a view different to render than last-controller/last-action public registerEngines( array $engines ) Register templating engines public ViewInterface|bool render(string $controllerName,string $actionName,array $params = []) Executes render process from dispatching data public reset() Resets the view component to its factory default values public setBasePath( string $basePath ) Sets base path. Depending of your platform, always add a trailing slash public setLayout( string $layout ) Change the layout to be used instead of using the name of the latest public setLayoutsDir( string $layoutsDir ) Sets the layouts sub-directory. Must be a directory under the views public setMainView( string $viewPath ) Sets default view name. Must be a file without extension in the views public setPartialsDir( string $partialsDir ) Sets a partials sub-directory. Must be a directory under the views public ViewInterface setRenderLevel( int $level ) Sets the render level for the view public setTemplateAfter( mixed $templateAfter ) Appends template after controller layout public setTemplateBefore( mixed $templateBefore ) Appends template before controller layout public start() Starts rendering process enabling the output buffering
### Methods
Public · 27
#### `cleanTemplateAfter()` { #mvcviewinterface-cleantemplateafter }
public function cleanTemplateAfter();
Resets any template before layouts #### `cleanTemplateBefore()` { #mvcviewinterface-cleantemplatebefore }
public function cleanTemplateBefore();
Resets any template before layouts #### `disable()` { #mvcviewinterface-disable }
public function disable();
Disables the auto-rendering process #### `enable()` { #mvcviewinterface-enable }
public function enable();
Enables the auto-rendering process #### `finish()` { #mvcviewinterface-finish }
public function finish();
Finishes the render process by stopping the output buffering #### `getActionName()` { #mvcviewinterface-getactionname }
public function getActionName(): string;
Gets the name of the action rendered #### `getActiveRenderPath()` { #mvcviewinterface-getactiverenderpath }
public function getActiveRenderPath(): string|array;
Returns the path of the view that is currently rendered #### `getBasePath()` { #mvcviewinterface-getbasepath }
public function getBasePath(): string;
Gets base path #### `getControllerName()` { #mvcviewinterface-getcontrollername }
public function getControllerName(): string;
Gets the name of the controller rendered #### `getLayout()` { #mvcviewinterface-getlayout }
public function getLayout(): string|null;
Returns the name of the main view #### `getLayoutsDir()` { #mvcviewinterface-getlayoutsdir }
public function getLayoutsDir(): string;
Gets the current layouts sub-directory #### `getMainView()` { #mvcviewinterface-getmainview }
public function getMainView(): string;
Returns the name of the main view #### `getPartialsDir()` { #mvcviewinterface-getpartialsdir }
public function getPartialsDir(): string;
Gets the current partials sub-directory #### `isDisabled()` { #mvcviewinterface-isdisabled }
public function isDisabled(): bool;
Whether the automatic rendering is disabled #### `pick()` { #mvcviewinterface-pick }
public function pick( string $renderView );
Choose a view different to render than last-controller/last-action #### `registerEngines()` { #mvcviewinterface-registerengines }
public function registerEngines( array $engines );
Register templating engines #### `render()` { #mvcviewinterface-render }
public function render(
    string $controllerName,
    string $actionName,
    array $params = []
): ViewInterface|bool;
Executes render process from dispatching data #### `reset()` { #mvcviewinterface-reset }
public function reset();
Resets the view component to its factory default values #### `setBasePath()` { #mvcviewinterface-setbasepath }
public function setBasePath( string $basePath );
Sets base path. Depending of your platform, always add a trailing slash or backslash #### `setLayout()` { #mvcviewinterface-setlayout }
public function setLayout( string $layout );
Change the layout to be used instead of using the name of the latest controller name #### `setLayoutsDir()` { #mvcviewinterface-setlayoutsdir }
public function setLayoutsDir( string $layoutsDir );
Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash #### `setMainView()` { #mvcviewinterface-setmainview }
public function setMainView( string $viewPath );
Sets default view name. Must be a file without extension in the views directory #### `setPartialsDir()` { #mvcviewinterface-setpartialsdir }
public function setPartialsDir( string $partialsDir );
Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash #### `setRenderLevel()` { #mvcviewinterface-setrenderlevel }
public function setRenderLevel( int $level ): ViewInterface;
Sets the render level for the view #### `setTemplateAfter()` { #mvcviewinterface-settemplateafter }
public function setTemplateAfter( mixed $templateAfter );
Appends template after controller layout #### `setTemplateBefore()` { #mvcviewinterface-settemplatebefore }
public function setTemplateBefore( mixed $templateBefore );
Appends template before controller layout #### `start()` { #mvcviewinterface-start }
public function start();
Starts rendering process enabling the output buffering ## Mvc\View\Engine\AbstractEngine Abstract [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/AbstractEngine.zep){ .src-btn } All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\Mvc\View component.
- `stdClass` - [`Phalcon\Di\Injectable`](phalcon_di.md#diinjectable) - **`Phalcon\Mvc\View\Engine\AbstractEngine`** — implements [`Phalcon\Mvc\View\Engine\EngineInterface`](#mvcviewengineengineinterface), [`Phalcon\Events\EventsAwareInterface`](phalcon_events.md#eventseventsawareinterface) - [`Phalcon\Mvc\View\Engine\Php`](#mvcviewenginephp) - [`Phalcon\Mvc\View\Engine\Volt`](#mvcviewenginevolt)
__Uses__ `Phalcon\Di\DiInterface` · `Phalcon\Di\Injectable` · `Phalcon\Events\EventsAwareInterface` · `Phalcon\Events\ManagerInterface` · `Phalcon\Mvc\ViewBaseInterface` { .api-uses } ### Method Summary ### Properties
protected ManagerInterface|null $eventsManager = null
protected ViewBaseInterface $view
### Methods
Public · 6
#### `__construct()` { #mvcviewengineabstractengine-__construct }
public function __construct(
    ViewBaseInterface $view,
    DiInterface $container = null
);
Phalcon\Mvc\View\Engine constructor #### `getContent()` { #mvcviewengineabstractengine-getcontent }
public function getContent(): string;
Returns cached output on another view stage #### `getEventsManager()` { #mvcviewengineabstractengine-geteventsmanager }
public function getEventsManager(): ManagerInterface|null;
Returns the internal event manager #### `getView()` { #mvcviewengineabstractengine-getview }
public function getView(): ViewBaseInterface;
Returns the view component related to the adapter #### `partial()` { #mvcviewengineabstractengine-partial }
public function partial(
    string $partialPath,
    mixed $params = null
): void;
Renders a partial inside another view #### `setEventsManager()` { #mvcviewengineabstractengine-seteventsmanager }
public function setEventsManager( ManagerInterface $eventsManager ): void;
Sets the events manager
Protected · 1
#### `fireManagerEvent()` { #mvcviewengineabstractengine-firemanagerevent }
protected function fireManagerEvent(
    string $eventName,
    mixed $data = null,
    bool $cancellable = true
): mixed|bool;
Helper method to fire an event ## Mvc\View\Engine\EngineInterface Interface [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/EngineInterface.zep){ .src-btn } Interface for Phalcon\Mvc\View engine adapters
- **`Phalcon\Mvc\View\Engine\EngineInterface`**
### Method Summary ### Methods
Public · 3
#### `getContent()` { #mvcviewengineengineinterface-getcontent }
public function getContent(): string;
Returns cached output on another view stage #### `partial()` { #mvcviewengineengineinterface-partial }
public function partial(
    string $partialPath,
    mixed $params = null
): void;
Renders a partial inside another view #### `render()` { #mvcviewengineengineinterface-render }
public function render(
    string $path,
    mixed $params,
    bool $mustClean = false
);
Renders a view using the template engine TODO: Change params to array type ## Mvc\View\Engine\Php Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Php.zep){ .src-btn } Adapter to use PHP itself as templating engine
- `stdClass` - [`Phalcon\Di\Injectable`](phalcon_di.md#diinjectable) - [`Phalcon\Mvc\View\Engine\AbstractEngine`](#mvcviewengineabstractengine) - **`Phalcon\Mvc\View\Engine\Php`**
### Method Summary ### Methods
Public · 1
#### `render()` { #mvcviewenginephp-render }
public function render(
    string $path,
    mixed $params,
    bool $mustClean = false
);
Renders a view using the template engine ## Mvc\View\Engine\Volt Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt.zep){ .src-btn } Designer friendly and fast template engine for PHP written in Zephir/C
- `stdClass` - [`Phalcon\Di\Injectable`](phalcon_di.md#diinjectable) - [`Phalcon\Mvc\View\Engine\AbstractEngine`](#mvcviewengineabstractengine) - **`Phalcon\Mvc\View\Engine\Volt`** — implements [`Phalcon\Events\EventsAwareInterface`](phalcon_events.md#eventseventsawareinterface)
__Uses__ `Phalcon\Di\DiInterface` · `Phalcon\Events\EventsAwareInterface` · `Phalcon\Events\ManagerInterface` · `Phalcon\Html\Link\Link` · `Phalcon\Html\Link\Serializer\Header` · `Phalcon\Mvc\View\Engine\Volt\Compiler` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidHaystack` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroNotFound` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\MbstringRequired` · `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Properties
protected Compiler $compiler
protected ManagerInterface|null $eventsManager
protected array $macros = []
protected array $options = []
### Methods
Public · 13
#### `callMacro()` { #mvcviewenginevolt-callmacro }
public function callMacro(
    string $name,
    array $arguments = []
): mixed;
Checks if a macro is defined and calls it @params string name @params array arguments #### `convertEncoding()` { #mvcviewenginevolt-convertencoding }
public function convertEncoding(
    string $text,
    string $from,
    string $to
): string;
Performs a string conversion #### `getCompiler()` { #mvcviewenginevolt-getcompiler }
public function getCompiler(): Compiler;
Returns the Volt's compiler #### `getEventsManager()` { #mvcviewenginevolt-geteventsmanager }
public function getEventsManager(): ManagerInterface|null;
Returns the internal event manager #### `getOptions()` { #mvcviewenginevolt-getoptions }
public function getOptions(): array;
Return Volt's options #### `isIncluded()` { #mvcviewenginevolt-isincluded }
public function isIncluded(
    mixed $needle,
    mixed $haystack
): bool;
Checks if the needle is included in the haystack #### `length()` { #mvcviewenginevolt-length }
public function length( mixed $item ): int;
Length filter. If an array/object is passed a count is performed otherwise a strlen/mb_strlen #### `preload()` { #mvcviewenginevolt-preload }
public function preload( mixed $parameters ): string;
Parses the preload element passed and sets the necessary link headers @todo find a better way to handle this #### `render()` { #mvcviewenginevolt-render }
public function render(
    string $path,
    mixed $params,
    bool $mustClean = false
);
Renders a view using the template engine #### `setEventsManager()` { #mvcviewenginevolt-seteventsmanager }
public function setEventsManager( ManagerInterface $eventsManager ): void;
Sets the events manager #### `setOptions()` { #mvcviewenginevolt-setoptions }
public function setOptions( array $options );
Set Volt's options #### `slice()` { #mvcviewenginevolt-slice }
public function slice(
    mixed $value,
    int $start = 0,
    mixed $end = null
);
Extracts a slice from a string/array/traversable object value #### `sort()` { #mvcviewenginevolt-sort }
public function sort( array $value ): array;
Sorts an array ## Mvc\View\Engine\Volt\Compiler Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Compiler.zep){ .src-btn } This class reads and compiles Volt templates into PHP plain code
$compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler();

$compiler->compile("views/partials/header.volt");

require $compiler->getCompiledTemplatePath();
- **`Phalcon\Mvc\View\Engine\Volt\Compiler`** — implements [`Phalcon\Di\InjectionAwareInterface`](phalcon_di.md#diinjectionawareinterface)
__Uses__ `Closure` · `Phalcon\Di\DiInterface` · `Phalcon\Di\InjectionAwareInterface` · `Phalcon\Mvc\ViewBaseInterface` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatement` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidExtension` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidOptionType` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathType` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidStatement` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement` · `Phalcon\Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable` { .api-uses } ### Method Summary
public __construct( ViewBaseInterface $view = null ) Phalcon\Mvc\View\Engine\Volt\Compiler public static addExtension( mixed $extension ) Registers a Volt's extension public static addFilter(string $name,mixed $definition) Register a new filter in the compiler public static addFunction(string $name,mixed $definition) Register a new function in the compiler public string attributeReader( array $expr ) Resolves attribute reading public compile(string $templatePath,bool $extendsMode = false) Compiles a template into a file applying the compiler options public string compileAutoEscape(array $statement,bool $extendsMode) Compiles a "autoescape" statement returning PHP code public string compileCall(array $statement,bool $extendsMode) Compiles calls to macros public string compileCase(array $statement,bool $caseClause = true) Compiles a "case"/"default" clause returning PHP code public string compileDo( array $statement ) Compiles a "do" statement returning PHP code public string compileEcho( array $statement ) Compiles a {{ }} statement returning PHP code public string compileElseIf( array $statement ) Compiles a "elseif" statement returning PHP code public compileFile(string $path,string $compiledPath,bool $extendsMode = false) Compiles a template into a file forcing the destination path public string compileForElse() Generates a 'forelse' PHP code public string compileForeach(array $statement,bool $extendsMode = false) Compiles a "foreach" intermediate code representation into plain PHP code public string compileIf(array $statement,bool $extendsMode = false) Compiles a 'if' statement returning PHP code public string compileInclude( array $statement ) Compiles a 'include' statement returning PHP code public string compileMacro(array $statement,bool $extendsMode) Compiles macros public string compileReturn( array $statement ) Compiles a "return" statement returning PHP code public string compileSet( array $statement ) Compiles a "set" statement returning PHP code. The method accepts an public string compileString(string $viewCode,bool $extendsMode = false) Compiles a template into a string public string compileSwitch(array $statement,bool $extendsMode = false) Compiles a 'switch' statement returning PHP code public string expression(array $expr,bool $doubleQuotes = false) Resolves an expression node in an AST volt tree public fireExtensionEvent(string $name,array $arguments = []) Fires an event to registered extensions public string functionCall(array $expr,bool $doubleQuotes = false) Resolves function intermediate code into PHP function calls public string getCompiledTemplatePath() Returns the path to the last compiled template public DiInterface getDI() Returns the internal dependency injector public array getExtensions() Returns the list of extensions registered in Volt public array getFilters() Register the user registered filters public array getFunctions() Register the user registered functions public string|null getOption( string $option ) Returns a compiler's option public array getOptions() Returns the compiler options public string getTemplatePath() Returns the path that is currently being compiled public string getUniquePrefix() Return a unique prefix to be used as prefix for compiled variables and public array parse( string $viewCode ) Parses a Volt template returning its intermediate representation public string resolveTest(array $test,string $left) Resolves filter intermediate code into a valid PHP expression public void setDI( DiInterface $container ) Sets the dependency injector public static setOption(string $option,mixed $value) Sets a single compiler option public static setOptions( array $options ) Sets the compiler options public static setUniquePrefix( string $prefix ) Set a unique prefix to be used as prefix for compiled variables protected array|string compileSource(string $viewCode,bool $extendsMode = false) Compiles a Volt source code returning a PHP plain version protected getFinalPath( string $path ) Gets the final path with VIEW protected string resolveFilter(array $filter,string $left) Resolves filter intermediate code into PHP function calls protected string statementList(array $statements,bool $extendsMode = false) Traverses a statement list compiling each of its nodes protected statementListOrExtends( mixed $statements ) Compiles a block of statements
### Properties
protected bool $autoescape = false
protected int $blockLevel = 0
protected array|null $blocks TODO: Make array only?
protected string|null $compiledTemplatePath
protected DiInterface|null $container = null
protected string|null $currentBlock = null
protected string|null $currentPath = null
protected int $exprLevel = 0
protected bool $extended = false
protected array|bool $extendedBlocks TODO: Make it always array
protected array $extensions = []
protected array $filters = []
protected array $forElsePointers = []
protected int $foreachLevel = 0
protected array $functions = []
protected int $level = 0
protected array $loopPointers = []
protected array $macros = []
protected array $options = []
protected string $prefix = ""
protected ViewBaseInterface|null $view
### Methods
Public · 40
#### `__construct()` { #mvcviewenginevoltcompiler-__construct }
public function __construct( ViewBaseInterface $view = null );
Phalcon\Mvc\View\Engine\Volt\Compiler #### `addExtension()` { #mvcviewenginevoltcompiler-addextension }
public function addExtension( mixed $extension ): static;
Registers a Volt's extension #### `addFilter()` { #mvcviewenginevoltcompiler-addfilter }
public function addFilter(
    string $name,
    mixed $definition
): static;
Register a new filter in the compiler #### `addFunction()` { #mvcviewenginevoltcompiler-addfunction }
public function addFunction(
    string $name,
    mixed $definition
): static;
Register a new function in the compiler #### `attributeReader()` { #mvcviewenginevoltcompiler-attributereader }
public function attributeReader( array $expr ): string;
Resolves attribute reading #### `compile()` { #mvcviewenginevoltcompiler-compile }
public function compile(
    string $templatePath,
    bool $extendsMode = false
);
Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled
$compiler->compile("views/layouts/main.volt");

require $compiler->getCompiledTemplatePath();
#### `compileAutoEscape()` { #mvcviewenginevoltcompiler-compileautoescape }
public function compileAutoEscape(
    array $statement,
    bool $extendsMode
): string;
Compiles a "autoescape" statement returning PHP code #### `compileCall()` { #mvcviewenginevoltcompiler-compilecall }
public function compileCall(
    array $statement,
    bool $extendsMode
): string;
Compiles calls to macros #### `compileCase()` { #mvcviewenginevoltcompiler-compilecase }
public function compileCase(
    array $statement,
    bool $caseClause = true
): string;
Compiles a "case"/"default" clause returning PHP code #### `compileDo()` { #mvcviewenginevoltcompiler-compiledo }
public function compileDo( array $statement ): string;
Compiles a "do" statement returning PHP code #### `compileEcho()` { #mvcviewenginevoltcompiler-compileecho }
public function compileEcho( array $statement ): string;
Compiles a `{{` `}}` statement returning PHP code #### `compileElseIf()` { #mvcviewenginevoltcompiler-compileelseif }
public function compileElseIf( array $statement ): string;
Compiles a "elseif" statement returning PHP code #### `compileFile()` { #mvcviewenginevoltcompiler-compilefile }
public function compileFile(
    string $path,
    string $compiledPath,
    bool $extendsMode = false
);
Compiles a template into a file forcing the destination path
$compiler->compileFile(
    "views/layouts/main.volt",
    "views/layouts/main.volt.php"
);
#### `compileForElse()` { #mvcviewenginevoltcompiler-compileforelse }
public function compileForElse(): string;
Generates a 'forelse' PHP code #### `compileForeach()` { #mvcviewenginevoltcompiler-compileforeach }
public function compileForeach(
    array $statement,
    bool $extendsMode = false
): string;
Compiles a "foreach" intermediate code representation into plain PHP code #### `compileIf()` { #mvcviewenginevoltcompiler-compileif }
public function compileIf(
    array $statement,
    bool $extendsMode = false
): string;
Compiles a 'if' statement returning PHP code #### `compileInclude()` { #mvcviewenginevoltcompiler-compileinclude }
public function compileInclude( array $statement ): string;
Compiles a 'include' statement returning PHP code #### `compileMacro()` { #mvcviewenginevoltcompiler-compilemacro }
public function compileMacro(
    array $statement,
    bool $extendsMode
): string;
Compiles macros #### `compileReturn()` { #mvcviewenginevoltcompiler-compilereturn }
public function compileReturn( array $statement ): string;
Compiles a "return" statement returning PHP code #### `compileSet()` { #mvcviewenginevoltcompiler-compileset }
public function compileSet( array $statement ): string;
Compiles a "set" statement returning PHP code. The method accepts an array produced by the Volt parser and creates the `set` statement in PHP. This method is not particularly useful in development, since it requires advanced knowledge of the Volt parser.
<?php

use Phalcon\Mvc\View\Engine\Volt\Compiler;

$compiler = new Compiler();

// {% set a = ['first': 1] %}

$source = [
    "type" => 306,
    "assignments" => [
        [
            "variable" => [
                "type" => 265,
                "value" => "a",
                "file" => "eval code",
                "line" => 1
            ],
            "op" => 61,
            "expr" => [
                "type" => 360,
                "left" => [
                    [
                        "expr" => [
                            "type" => 258,
                            "value" => "1",
                            "file" => "eval code",
                            "line" => 1
                        ],
                        "name" => "first",
                        "file" => "eval code",
                        "line" => 1
                    ]
                ],
                "file" => "eval code",
                "line" => 1
            ],
            "file" => "eval code",
            "line" => 1
        ]
    ]
];

echo $compiler->compileSet($source);
// <?php $a = ['first' => 1]; ?>";
#### `compileString()` { #mvcviewenginevoltcompiler-compilestring }
public function compileString(
    string $viewCode,
    bool $extendsMode = false
): string;
Compiles a template into a string
echo $compiler->compileString('{{ "hello world" }}');
#### `compileSwitch()` { #mvcviewenginevoltcompiler-compileswitch }
public function compileSwitch(
    array $statement,
    bool $extendsMode = false
): string;
Compiles a 'switch' statement returning PHP code #### `expression()` { #mvcviewenginevoltcompiler-expression }
final public function expression(
    array $expr,
    bool $doubleQuotes = false
): string;
Resolves an expression node in an AST volt tree #### `fireExtensionEvent()` { #mvcviewenginevoltcompiler-fireextensionevent }
final public function fireExtensionEvent(
    string $name,
    array $arguments = []
);
Fires an event to registered extensions #### `functionCall()` { #mvcviewenginevoltcompiler-functioncall }
public function functionCall(
    array $expr,
    bool $doubleQuotes = false
): string;
Resolves function intermediate code into PHP function calls #### `getCompiledTemplatePath()` { #mvcviewenginevoltcompiler-getcompiledtemplatepath }
public function getCompiledTemplatePath(): string;
Returns the path to the last compiled template #### `getDI()` { #mvcviewenginevoltcompiler-getdi }
public function getDI(): DiInterface;
Returns the internal dependency injector #### `getExtensions()` { #mvcviewenginevoltcompiler-getextensions }
public function getExtensions(): array;
Returns the list of extensions registered in Volt #### `getFilters()` { #mvcviewenginevoltcompiler-getfilters }
public function getFilters(): array;
Register the user registered filters #### `getFunctions()` { #mvcviewenginevoltcompiler-getfunctions }
public function getFunctions(): array;
Register the user registered functions #### `getOption()` { #mvcviewenginevoltcompiler-getoption }
public function getOption( string $option ): string|null;
Returns a compiler's option #### `getOptions()` { #mvcviewenginevoltcompiler-getoptions }
public function getOptions(): array;
Returns the compiler options #### `getTemplatePath()` { #mvcviewenginevoltcompiler-gettemplatepath }
public function getTemplatePath(): string;
Returns the path that is currently being compiled #### `getUniquePrefix()` { #mvcviewenginevoltcompiler-getuniqueprefix }
public function getUniquePrefix(): string;
Return a unique prefix to be used as prefix for compiled variables and contexts #### `parse()` { #mvcviewenginevoltcompiler-parse }
public function parse( string $viewCode ): array;
Parses a Volt template returning its intermediate representation
print_r(
    $compiler->parse("{{ 3 + 2 }}")
);
#### `resolveTest()` { #mvcviewenginevoltcompiler-resolvetest }
public function resolveTest(
    array $test,
    string $left
): string;
Resolves filter intermediate code into a valid PHP expression #### `setDI()` { #mvcviewenginevoltcompiler-setdi }
public function setDI( DiInterface $container ): void;
Sets the dependency injector #### `setOption()` { #mvcviewenginevoltcompiler-setoption }
public function setOption(
    string $option,
    mixed $value
): static;
Sets a single compiler option #### `setOptions()` { #mvcviewenginevoltcompiler-setoptions }
public function setOptions( array $options ): static;
Sets the compiler options #### `setUniquePrefix()` { #mvcviewenginevoltcompiler-setuniqueprefix }
public function setUniquePrefix( string $prefix ): static;
Set a unique prefix to be used as prefix for compiled variables
Protected · 5
#### `compileSource()` { #mvcviewenginevoltcompiler-compilesource }
protected function compileSource(
    string $viewCode,
    bool $extendsMode = false
): array|string;
Compiles a Volt source code returning a PHP plain version #### `getFinalPath()` { #mvcviewenginevoltcompiler-getfinalpath }
protected function getFinalPath( string $path );
Gets the final path with VIEW #### `resolveFilter()` { #mvcviewenginevoltcompiler-resolvefilter }
final protected function resolveFilter(
    array $filter,
    string $left
): string;
Resolves filter intermediate code into PHP function calls #### `statementList()` { #mvcviewenginevoltcompiler-statementlist }
final protected function statementList(
    array $statements,
    bool $extendsMode = false
): string;
Traverses a statement list compiling each of its nodes #### `statementListOrExtends()` { #mvcviewenginevoltcompiler-statementlistorextends }
final protected function statementListOrExtends( mixed $statements );
Compiles a block of statements ## Mvc\View\Engine\Volt\Exception Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exception.zep){ .src-btn } Class for exceptions thrown by Phalcon\Mvc\View
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Engine\Volt\Exception`** - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile`](#mvcviewenginevoltexceptionscannotopencompiledfile) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatement`](#mvcviewenginevoltexceptionscorruptedstatement) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData`](#mvcviewenginevoltexceptionscorruptedstatementwithdata) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix`](#mvcviewenginevoltexceptionsinvalidcompilationprefix) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidExtension`](#mvcviewenginevoltexceptionsinvalidextension) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidHaystack`](#mvcviewenginevoltexceptionsinvalidhaystack) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation`](#mvcviewenginevoltexceptionsinvalidintermediaterepresentation) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidOptionType`](#mvcviewenginevoltexceptionsinvalidoptiontype) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn`](#mvcviewenginevoltexceptionsinvalidpathclosurereturn) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathType`](#mvcviewenginevoltexceptionsinvalidpathtype) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidStatement`](#mvcviewenginevoltexceptionsinvalidstatement) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition`](#mvcviewenginevoltexceptionsinvaliduserfilterdefinition) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition`](#mvcviewenginevoltexceptionsinvaliduserfunctiondefinition) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined`](#mvcviewenginevoltexceptionsmacroalreadydefined) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroNotFound`](#mvcviewenginevoltexceptionsmacronotfound) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\MbstringRequired`](#mvcviewenginevoltexceptionsmbstringrequired) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound`](#mvcviewenginevoltexceptionstemplatefilenotfound) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable`](#mvcviewenginevoltexceptionstemplatefilenotopenable) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision`](#mvcviewenginevoltexceptionstemplatepathcollision) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression`](#mvcviewenginevoltexceptionsunknownvoltexpression) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter`](#mvcviewenginevoltexceptionsunknownvoltfilter) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType`](#mvcviewenginevoltexceptionsunknownvoltfiltertype) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement`](#mvcviewenginevoltexceptionsunknownvoltstatement) - [`Phalcon\Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable`](#mvcviewenginevoltexceptionsvoltdirectorynotwritable)
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Properties
protected array $statement = []
### Methods
Public · 2
#### `__construct()` { #mvcviewenginevoltexception-__construct }
public function __construct(
    string $message = "",
    array $statement = [],
    int $code = 0,
    \Exception $previous = null
);
#### `getStatement()` { #mvcviewenginevoltexception-getstatement }
public function getStatement(): array;
Gets currently parsed statement (if any). ## Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/CannotOpenCompiledFile.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionscannotopencompiledfile-__construct }
public function __construct( string $path );
## Mvc\View\Engine\Volt\Exceptions\CorruptedStatement Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/CorruptedStatement.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatement`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionscorruptedstatement-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/CorruptedStatementWithData.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionscorruptedstatementwithdata-__construct }
public function __construct( array $statement );
## Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidCompilationPrefix.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidcompilationprefix-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\InvalidExtension Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidExtension.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidExtension`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidextension-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\InvalidHaystack Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidHaystack.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidHaystack`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidhaystack-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidIntermediateRepresentation.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidintermediaterepresentation-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\InvalidOptionType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidOptionType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidOptionType`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidoptiontype-__construct }
public function __construct(
    string $option,
    string $type
);
## Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidPathClosureReturn.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidpathclosurereturn-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\InvalidPathType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidPathType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathType`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidpathtype-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\InvalidStatement Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidStatement.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidStatement`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvalidstatement-__construct }
public function __construct(
    string $file,
    int $line,
    array $statement
);
## Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidUserFilterDefinition.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvaliduserfilterdefinition-__construct }
public function __construct(
    string $name,
    string $file,
    int $line
);
## Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/InvalidUserFunctionDefinition.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsinvaliduserfunctiondefinition-__construct }
public function __construct(
    string $name,
    string $file,
    int $line
);
## Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/MacroAlreadyDefined.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsmacroalreadydefined-__construct }
public function __construct( string $name );
## Mvc\View\Engine\Volt\Exceptions\MacroNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/MacroNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroNotFound`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsmacronotfound-__construct }
public function __construct( string $name );
## Mvc\View\Engine\Volt\Exceptions\MbstringRequired Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/MbstringRequired.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\MbstringRequired`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsmbstringrequired-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/TemplateFileNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionstemplatefilenotfound-__construct }
public function __construct( string $path );
## Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/TemplateFileNotOpenable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionstemplatefilenotopenable-__construct }
public function __construct( string $path );
## Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/TemplatePathCollision.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionstemplatepathcollision-__construct }
public function __construct();
## Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/UnknownVoltExpression.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsunknownvoltexpression-__construct }
public function __construct(
    int $type,
    string $file,
    int $line
);
## Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/UnknownVoltFilter.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsunknownvoltfilter-__construct }
public function __construct(
    string $name,
    string $file,
    int $line
);
## Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/UnknownVoltFilterType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsunknownvoltfiltertype-__construct }
public function __construct(
    string $file,
    int $line
);
## Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/UnknownVoltStatement.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsunknownvoltstatement-__construct }
public function __construct(
    int $type,
    string $file,
    int $line
);
## Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Engine/Volt/Exceptions/VoltDirectoryNotWritable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - **`Phalcon\Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable`**
__Uses__ `Phalcon\Mvc\View\Engine\Volt\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewenginevoltexceptionsvoltdirectorynotwritable-__construct }
public function __construct();
## Mvc\View\Exception Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exception.zep){ .src-btn } Phalcon\Mvc\View\Exception Class for exceptions thrown by Phalcon\Mvc\View
- `\Exception` - **`Phalcon\Mvc\View\Exception`** - [`Phalcon\Mvc\View\Engine\Volt\Exception`](#mvcviewenginevoltexception) - [`Phalcon\Mvc\View\Exceptions\InvalidEngineRegistration`](#mvcviewexceptionsinvalidengineregistration) - [`Phalcon\Mvc\View\Exceptions\InvalidViewsDirType`](#mvcviewexceptionsinvalidviewsdirtype) - [`Phalcon\Mvc\View\Exceptions\SimpleViewNotFound`](#mvcviewexceptionssimpleviewnotfound) - [`Phalcon\Mvc\View\Exceptions\SimpleViewServicesUnavailable`](#mvcviewexceptionssimpleviewservicesunavailable) - [`Phalcon\Mvc\View\Exceptions\ViewNotFound`](#mvcviewexceptionsviewnotfound) - [`Phalcon\Mvc\View\Exceptions\ViewServicesUnavailable`](#mvcviewexceptionsviewservicesunavailable) - [`Phalcon\Mvc\View\Exceptions\ViewsDirItemMustBeString`](#mvcviewexceptionsviewsdiritemmustbestring)
## Mvc\View\Exceptions\InvalidEngineRegistration Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exceptions/InvalidEngineRegistration.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Exceptions\InvalidEngineRegistration`**
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewexceptionsinvalidengineregistration-__construct }
public function __construct( string $extension );
## Mvc\View\Exceptions\InvalidViewsDirType Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exceptions/InvalidViewsDirType.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Exceptions\InvalidViewsDirType`**
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewexceptionsinvalidviewsdirtype-__construct }
public function __construct();
## Mvc\View\Exceptions\SimpleViewNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exceptions/SimpleViewNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Exceptions\SimpleViewNotFound`**
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewexceptionssimpleviewnotfound-__construct }
public function __construct( string $viewsDirPath );
## Mvc\View\Exceptions\SimpleViewServicesUnavailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exceptions/SimpleViewServicesUnavailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Exceptions\SimpleViewServicesUnavailable`**
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewexceptionssimpleviewservicesunavailable-__construct }
public function __construct();
## Mvc\View\Exceptions\ViewNotFound Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exceptions/ViewNotFound.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Exceptions\ViewNotFound`**
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewexceptionsviewnotfound-__construct }
public function __construct( string $viewPath );
## Mvc\View\Exceptions\ViewServicesUnavailable Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exceptions/ViewServicesUnavailable.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Exceptions\ViewServicesUnavailable`**
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewexceptionsviewservicesunavailable-__construct }
public function __construct();
## Mvc\View\Exceptions\ViewsDirItemMustBeString Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Exceptions/ViewsDirItemMustBeString.zep){ .src-btn }
- `\Exception` - [`Phalcon\Mvc\View\Exception`](#mvcviewexception) - **`Phalcon\Mvc\View\Exceptions\ViewsDirItemMustBeString`**
__Uses__ `Phalcon\Mvc\View\Exception` { .api-uses } ### Method Summary ### Methods
Public · 1
#### `__construct()` { #mvcviewexceptionsviewsdiritemmustbestring-__construct }
public function __construct();
## Mvc\View\Simple Class [:material-github: Source on GitHub](https://github.com/phalcon/cphalcon/blob/5.0.x/phalcon/Mvc/View/Simple.zep){ .src-btn } This component allows to render views without hierarchical levels
use Phalcon\Mvc\View\Simple as View;

$view = new View();

// Render a view
echo $view->render(
    "templates/my-view",
    [
        "some" => $param,
    ]
);

// Or with filename with extension
echo $view->render(
    "templates/my-view.volt",
    [
        "parameter" => $here,
    ]
);
- `stdClass` - [`Phalcon\Di\Injectable`](phalcon_di.md#diinjectable) - **`Phalcon\Mvc\View\Simple`** — implements [`Phalcon\Mvc\ViewBaseInterface`](#mvcviewbaseinterface), [`Phalcon\Events\EventsAwareInterface`](phalcon_events.md#eventseventsawareinterface)
__Uses__ `Closure` · `Phalcon\Di\DiInterface` · `Phalcon\Di\Injectable` · `Phalcon\Events\EventsAwareInterface` · `Phalcon\Events\ManagerInterface` · `Phalcon\Mvc\ViewBaseInterface` · `Phalcon\Mvc\View\Engine\EngineInterface` · `Phalcon\Mvc\View\Engine\Php` · `Phalcon\Mvc\View\Exceptions\InvalidEngineRegistration` · `Phalcon\Mvc\View\Exceptions\SimpleViewNotFound` · `Phalcon\Mvc\View\Exceptions\SimpleViewServicesUnavailable` { .api-uses } ### Method Summary
public __construct( array $options = [] ) Phalcon\Mvc\View\Simple constructor public mixed|null __get( string $key ) Magic method to retrieve a variable passed to the view public void __set(string $key,mixed $value) Magic method to pass variables to the views public string getActiveRenderPath() Returns the path of the view that is currently rendered public string getContent() Returns output from another view stage public ManagerInterface|null getEventsManager() Returns the internal event manager public array getParamsToView() Returns parameters to views public array getRegisteredEngines() public mixed|null getVar( string $key ) Returns a parameter previously set in the view public string getViewsDir() Gets views directory public void partial(string $partialPath,mixed $params = null) Renders a partial view public void registerEngines( array $engines ) Register templating engines public string render(string $path,array $params = []) Renders a view public static setContent( string $content ) Externally sets the view content public void setEventsManager( ManagerInterface $eventsManager ) Sets the events manager public static setParamToView(string $key,mixed $value) Adds parameters to views (alias of setVar) public static setVar(string $key,mixed $value) Set a single view parameter public static setVars(array $params,bool $merge = true) Set all the render params public void setViewsDir( string $viewsDir ) Sets views directory protected void internalRender(string $path,mixed $params) Tries to render the view with every engine registered in the component protected array loadTemplateEngines() Loads registered template engines, if none are registered it will use
### Properties
protected string $activeRenderPath
protected string $content
protected EngineInterface[]|false $engines = false
protected ManagerInterface|null $eventsManager
protected array $options = []
protected array $registeredEngines = []
protected array $viewParams = []
protected string $viewsDir
### Methods
Public · 19
#### `__construct()` { #mvcviewsimple-__construct }
public function __construct( array $options = [] );
Phalcon\Mvc\View\Simple constructor #### `__get()` { #mvcviewsimple-__get }
public function __get( string $key ): mixed|null;
Magic method to retrieve a variable passed to the view
echo $this->view->products;
#### `__set()` { #mvcviewsimple-__set }
public function __set(
    string $key,
    mixed $value
): void;
Magic method to pass variables to the views
$this->view->products = $products;
#### `getActiveRenderPath()` { #mvcviewsimple-getactiverenderpath }
public function getActiveRenderPath(): string;
Returns the path of the view that is currently rendered #### `getContent()` { #mvcviewsimple-getcontent }
public function getContent(): string;
Returns output from another view stage #### `getEventsManager()` { #mvcviewsimple-geteventsmanager }
public function getEventsManager(): ManagerInterface|null;
Returns the internal event manager #### `getParamsToView()` { #mvcviewsimple-getparamstoview }
public function getParamsToView(): array;
Returns parameters to views #### `getRegisteredEngines()` { #mvcviewsimple-getregisteredengines }
public function getRegisteredEngines(): array;
#### `getVar()` { #mvcviewsimple-getvar }
public function getVar( string $key ): mixed|null;
Returns a parameter previously set in the view #### `getViewsDir()` { #mvcviewsimple-getviewsdir }
public function getViewsDir(): string;
Gets views directory #### `partial()` { #mvcviewsimple-partial }
public function partial(
    string $partialPath,
    mixed $params = null
): void;
Renders a partial view
// Show a partial inside another view
$this->partial("shared/footer");
// Show a partial inside another view with parameters
$this->partial(
    "shared/footer",
    [
        "content" => $html,
    ]
);
#### `registerEngines()` { #mvcviewsimple-registerengines }
public function registerEngines( array $engines ): void;
Register templating engines
$this->view->registerEngines(
    [
        ".phtml" => \Phalcon\Mvc\View\Engine\Php::class,
        ".volt"  => \Phalcon\Mvc\View\Engine\Volt::class,
        ".mhtml" => \MyCustomEngine::class,
    ]
);
#### `render()` { #mvcviewsimple-render }
public function render(
    string $path,
    array $params = []
): string;
Renders a view #### `setContent()` { #mvcviewsimple-setcontent }
public function setContent( string $content ): static;
Externally sets the view content
$this->view->setContent("<h1>hello</h1>");
#### `setEventsManager()` { #mvcviewsimple-seteventsmanager }
public function setEventsManager( ManagerInterface $eventsManager ): void;
Sets the events manager #### `setParamToView()` { #mvcviewsimple-setparamtoview }
public function setParamToView(
    string $key,
    mixed $value
): static;
Adds parameters to views (alias of setVar)
$this->view->setParamToView("products", $products);
#### `setVar()` { #mvcviewsimple-setvar }
public function setVar(
    string $key,
    mixed $value
): static;
Set a single view parameter
$this->view->setVar("products", $products);
#### `setVars()` { #mvcviewsimple-setvars }
public function setVars(
    array $params,
    bool $merge = true
): static;
Set all the render params
$this->view->setVars(
    [
        "products" => $products,
    ]
);
#### `setViewsDir()` { #mvcviewsimple-setviewsdir }
public function setViewsDir( string $viewsDir ): void;
Sets views directory
Protected · 2
#### `internalRender()` { #mvcviewsimple-internalrender }
final protected function internalRender(
    string $path,
    mixed $params
): void;
Tries to render the view with every engine registered in the component #### `loadTemplateEngines()` { #mvcviewsimple-loadtemplateengines }
protected function loadTemplateEngines(): array;
Loads registered template engines, if none are registered it will use Phalcon\Mvc\View\Engine\Php ?>