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 · Phalcon\Traits\Php\FileTrait

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.

$invoice = new Invoices();

$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;

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

    $messages = $invoice->getMessages();

    foreach ($messages as $message) {
        echo $message;
    }
} else {
    echo "Great, a new invoice 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\Hydration\CloneResultMapHydrate · 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 · ReflectionClass · ReflectionProperty

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 Invoices 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 Invoices extends Model
{
    public function beforeSave()
    {
        if ($this->name === "Peter") {
            $message = new Message(
                "Sorry, but an invoice 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

$invoice->assign(
    [
        "type" => "mechanical",
        "name" => "Test Invoice",
        "year" => 1952,
    ]
);

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

// Allow assign only name and year
$invoice->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);

$invoice->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 invoices?
$average = Invoices::average(
    [
        "column" => "inv_total",
    ]
);

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

// What's the average price of paid invoices?
$average = Invoices::average(
    [
        "inv_status_flag = 1",
        "column" => "inv_total",
    ]
);

echo "The average price of paid invoices 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

$invoice = Phalcon\Mvc\Model::cloneResult(
    new Invoices(),
    [
        "type" => "mechanical",
        "name" => "Test Invoice",
        "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.

$invoice = \Phalcon\Mvc\Model::cloneResultMap(
    new Invoices(),
    [
        "type" => "mechanical",
        "name" => "Test Invoice",
        "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 invoices are there?
$number = Invoices::count();

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

// How many paid invoices are there?
$number = Invoices::count("inv_status_flag = 1");

echo "There are ", $number, " paid invoices\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 invoice
$invoice = new Invoices();

$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;

$invoice->create();

// Passing an array to create
$invoice = new Invoices();

$invoice->assign(
    [
        "type" => "mechanical",
        "name" => "Test Invoice",
        "year" => 1952,
    ]
);

$invoice->create();

delete()

public function delete(): bool;

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

$invoice = Invoices::findFirst("id=100");

$invoice->delete();

$invoices = Invoices::find("inv_status_flag = 1");

foreach ($invoices as $invoice) {
    $invoice->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(
    $invoice->dump()
);

find()

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

Query for a set of records that match the specified conditions

// How many invoices are there?
$invoices = Invoices::find();

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

// How many paid invoices are there?
$invoices = Invoices::find(
    "inv_status_flag = 1"
);

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

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

foreach ($invoices as $invoice) {
    echo $invoice->inv_title, "\n";
}

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

foreach ($invoices as $invoice) {
    echo $invoice->inv_title, "\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();

$newInvoices = new Invoices();
$newInvoices->setTransaction($myTransaction);

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

$newInvoices->save();

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

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

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

foreach ($setOutsideTransaction as $invoice) {
    echo $invoice->inv_title, "\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 invoices
$firstNewInvoices = new Invoices();
$firstNewInvoices->setTransaction($myTransaction1);
$firstNewInvoices->assign(
    [
        'name' => 'first-transaction-invoice',
        'type' => 'mechanical',
        'year' => 1944,
    ]
);
$firstNewInvoices->save();

$secondNewInvoices = new Invoices();
$secondNewInvoices->setTransaction($myTransaction2);
$secondNewInvoices->assign(
    [
        'name' => 'second-transaction-invoice',
        'type' => 'fictional',
        'year' => 1984,
    ]
);
$secondNewInvoices->save();

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

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

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

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

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

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

$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 invoice in invoices table?
$invoice = Invoices::findFirst();

echo "The invoice name is ", $invoice->inv_title;

// What's the first paid invoice in invoices table?
$invoice = Invoices::findFirst(
    "inv_status_flag = 1"
);

echo "The first paid invoice name is ", $invoice->inv_title;

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

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

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

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

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

$doesNotFindAInvoices = Invoices::findFirst(
    [
        'name' => 'test',
    ]
);

var_dump($findAInvoices);
var_dump($doesNotFindAInvoices);

$transaction->commit();

$doesFindTheInvoicesNow = Invoices::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.

$invoices = Invoices::findFirst();
print_r($invoices->getChangedFields()); // []

$invoices->deleted = 'Y';

$invoices->getChangedFields();
print_r($invoices->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

$invoice = new Invoices();

$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;

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

    $messages = $invoice->getMessages();

    foreach ($messages as $message) {
        echo $message;
    }
} else {
    echo "Great, a new invoice 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.

$invoices = Invoices::findFirst();
print_r($invoices->getChangedFields()); // []

$invoices->deleted = 'Y';

$invoices->getChangedFields();
print_r($invoices->getChangedFields()); // ["deleted"]
$invoices->save();
print_r($invoices->getChangedFields()); // []
print_r($invoices->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

$invoice = new Invoices();

$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;

$invoice->create();

$invoice->inv_status_flag = "hydraulic";

$hasChanged = $invoice->hasChanged("type"); // returns true
$hasChanged = $invoice->hasChanged(["type", "name"]); // returns true
$hasChanged = $invoice->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.

$invoice = Invoices::findFirst();
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // false

$invoicesParts = $invoice->getOrdersProducts(['id > 0']);
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // false

$invoicesParts = $invoice->getOrdersProducts(); // or $invoice->ordersProducts
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // true

$invoice->ordersProducts = [new OrdersProducts()];
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // false

jsonSerialize()

public function jsonSerialize(): array;

Serializes the object for json_encode

echo json_encode($invoice);

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 invoice id?
$id = Invoices::maximum(
    [
        "column" => "id",
    ]
);

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

// What is the maximum id of paid invoices?
$sum = Invoices::maximum(
    [
        "inv_status_flag = 1",
        "column" => "id",
    ]
);

echo "The maximum invoice id of paid invoices 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 invoice id?
$id = Invoices::minimum(
    [
        "column" => "id",
    ]
);

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

// What is the minimum id of paid invoices?
$sum = Invoices::minimum(
    [
        "inv_status_flag = 1",
        "column" => "id",
    ]
);

echo "The minimum invoice id of paid invoices 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 $invoice->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 invoice
$invoice = new Invoices();

$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;

$invoice->save();

// Updating an invoice name
$invoice = Invoices::findFirst("id = 100");

$invoice->inv_title = "Biomass";

$invoice->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();

    $invoice = new Invoices();

    $invoice->setTransaction($transaction);

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

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

    $invoicePart = new OrdersProducts();

    $invoicePart->setTransaction($transaction);

    $invoicePart->type = "head";

    if ($invoicePart->save() === false) {
        $transaction->rollback("Invoices 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 invoices?
$sum = Invoices::sum(
    [
        "column" => "inv_total",
    ]
);

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

// How much are paid invoices?
$sum = Invoices::sum(
    [
        "inv_status_flag = 1",
        "column" => "inv_total",
    ]
);

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

toArray()

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

Returns the instance as an array representation

print_r(
    $invoice->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

$invoice->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 Invoices 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 OrdersProducts extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->belongsTo(
            "oxp_ord_id",
            Invoices::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 Invoices extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasMany(
            "id",
            OrdersProducts::class,
            "oxp_ord_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 Invoices extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        // Setup a many-to-many relation to Parts through OrdersProducts
        $this->hasManyToMany(
            "id",
            OrdersProducts::class,
            "oxp_ord_id",
            "oxp_prd_id",
            Products::class,
            "id",
        );
    }
}

hasOne()

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

Setup a 1-1 relation between two models

class Invoices extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->hasOne(
            "id",
            InvoicesDescription::class,
            "oxp_ord_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 Invoices extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        // Setup a 1-1 relation to one item from Parts through OrdersProducts
        $this->hasOneThrough(
            "id",
            OrdersProducts::class,
            "oxp_ord_id",
            "oxp_prd_id",
            Products::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 Invoices 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 Invoices 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 Invoices 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 Invoices 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 Invoices 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.

<?php

$invoices = Invoices::query()
    ->where("inv_cst_id = :customerId:")
    ->bind(["customerId" => 1])
    ->createBuilder();

distinct()

public function distinct( mixed $distinct ): CriteriaInterface;

Sets SELECT DISTINCT / SELECT ALL flag

execute()

public function execute(): ResultsetInterface;

Executes a find using the parameters built with the criteria

forUpdate()

public function forUpdate( bool $forUpdate = true ): CriteriaInterface;

Adds the "for_update" parameter to the criteria

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()

public function getColumns(): string|array|null;

Returns the columns to be queried

getConditions()

public function getConditions(): string|null;

Returns the conditions parameter in the criteria

getDI()

public function getDI(): DiInterface;

Returns the DependencyInjector container

getGroupBy()

public function getGroupBy();

Returns the group clause in the criteria

getHaving()

public function getHaving();

Returns the having clause in the criteria

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()

public function getModelName(): string;

Returns an internal model name on which the criteria will be applied

getOrderBy()

public function getOrderBy(): string|null;

Returns the order clause in the criteria

getParams()

public function getParams(): array;

Returns all the parameters defined in the criteria

getWhere()

public function getWhere(): string|null;

Returns the conditions parameter in the criteria

groupBy()

public function groupBy( mixed $group ): CriteriaInterface;

Adds the group-by clause to the criteria

having()

public function having( mixed $having ): CriteriaInterface;

Adds the having clause to the criteria

inWhere()

public function inWhere(
    string $expr,
    array $values
): CriteriaInterface;

Appends an IN condition to the current conditions

$criteria->inWhere("id", [1, 2, 3]);

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()

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()

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()

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()

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()

public function notInWhere(
    string $expr,
    array $values
): CriteriaInterface;

Appends a NOT IN condition to the current conditions

$criteria->notInWhere("id", [1, 2, 3]);

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()

public function orderBy( string $orderColumns ): CriteriaInterface;

Adds the order-by clause to the criteria

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()

public function setDI( DiInterface $container ): void;

Sets the DependencyInjector container

setModelName()

public function setModelName( string $modelName ): CriteriaInterface;

Set a model on which the query will be executed

sharedLock()

public function sharedLock( bool $sharedLock = true ): CriteriaInterface;

Adds the "shared_lock" parameter to the criteria

where()

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

Sets the conditions parameter in the criteria

Mvc\Model\CriteriaInterface

Interface Source on GitHub

Phalcon\Mvc\Model\CriteriaInterface

Interface for Phalcon\Mvc\Model\Criteria

  • Phalcon\Mvc\Model\CriteriaInterface

Uses Phalcon\Di\DiInterface

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()

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 ): 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

conditions()

public function conditions( string $conditions ): CriteriaInterface;

Adds the conditions parameter to the criteria

distinct()

public function distinct( mixed $distinct ): CriteriaInterface;

Sets SELECT DISTINCT / SELECT ALL flag

execute()

public function execute(): ResultsetInterface;

Executes a find using the parameters built with the criteria

forUpdate()

public function forUpdate( bool $forUpdate = true ): CriteriaInterface;

Sets the "for_update" parameter to the criteria

getColumns()

public function getColumns(): string|array|null;

Returns the columns to be queried

getConditions()

public function getConditions(): string|null;

Returns the conditions parameter in the criteria

getGroupBy()

public function getGroupBy();

Returns the group clause in the criteria

getHaving()

public function getHaving();

Returns the having clause in the criteria

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()

public function getModelName(): string;

Returns an internal model name on which the criteria will be applied

getOrderBy()

public function getOrderBy(): string|null;

Returns the order parameter in the criteria

getParams()

public function getParams(): array;

Returns all the parameters defined in the criteria

getWhere()

public function getWhere(): string|null;

Returns the conditions parameter in the criteria

groupBy()

public function groupBy( mixed $group ): CriteriaInterface;

Adds the group-by clause to the criteria

having()

public function having( mixed $having ): CriteriaInterface;

Adds the having clause to the criteria

inWhere()

public function inWhere(
    string $expr,
    array $values
): CriteriaInterface;

Appends an IN condition to the current conditions

$criteria->inWhere("id", [1, 2, 3]);

innerJoin()

public function innerJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;

Adds an INNER join to the query

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

$criteria->innerJoin(
    Orders::class,
    "r.ord_id = OrdersProducts.oxp_ord_id"
);

$criteria->innerJoin(
    Orders::class,
    "r.ord_id = OrdersProducts.oxp_ord_id",
    "r"
);

leftJoin()

public function leftJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;

Adds a LEFT join to the query

$criteria->leftJoin(
    Orders::class,
    "r.ord_id = OrdersProducts.oxp_ord_id",
    "r"
);

limit()

public function limit(
    int $limit,
    int $offset = 0
): CriteriaInterface;

Sets the limit parameter to the criteria

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()

public function notInWhere(
    string $expr,
    array $values
): CriteriaInterface;

Appends a NOT IN condition to the current conditions

$criteria->notInWhere("id", [1, 2, 3]);

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()

public function orderBy( string $orderColumns ): CriteriaInterface;

Adds the order-by parameter to the criteria

rightJoin()

public function rightJoin(
    string $model,
    mixed $conditions = null,
    mixed $alias = null
): CriteriaInterface;

Adds a RIGHT join to the query

$criteria->rightJoin(
    Orders::class,
    "r.ord_id = OrdersProducts.oxp_ord_id",
    "r"
);

setModelName()

public function setModelName( string $modelName ): CriteriaInterface;

Set a model on which the query will be executed

sharedLock()

public function sharedLock( bool $sharedLock = true ): CriteriaInterface;

Sets the "shared_lock" parameter to the criteria

where()

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

Sets the conditions parameter in the criteria

Mvc\Model\Exception

Class Source on GitHub

Phalcon\Mvc\Model\Exception

Exceptions thrown in Phalcon\Mvc\Model* classes will use this class

Mvc\Model\Exceptions\BelongsToRequiresObject

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $className,
    string $relationName
);

Mvc\Model\Exceptions\BindTypeNotDefined

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $column,
    string $className
);

Mvc\Model\Exceptions\CannotResolveAttribute

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $attribute,
    string $className
);

Mvc\Model\Exceptions\ColumnNotInMap

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $column,
    string $className
);

Mvc\Model\Exceptions\ColumnNotInTableColumns

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $column,
    string $className
);

Mvc\Model\Exceptions\ColumnNotInTableMap

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $column,
    string $className
);

Mvc\Model\Exceptions\CorruptColumnType

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\CursorIsImmutable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\DataTypeNotDefined

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $column,
    string $className
);

Mvc\Model\Exceptions\HandlerMustImplementBindable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\IdentityNotInColumnMap

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $identityField,
    string $className
);

Mvc\Model\Exceptions\IdentityNotInTableColumns

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $identityField,
    string $className
);

Mvc\Model\Exceptions\IndexNotInCursor

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\IndexNotInRow

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidConnectionService

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidContainer

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidDumpResultKey

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidFindParameters

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidGetModelNameReturn

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidModelName

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidModelsManagerService

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidModelsMetadataService

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidResultsetCacheService

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidReturnedRecord

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidSerializationData

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\ManagerOrmServicesUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\MethodNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $method,
    string $modelName
);

Mvc\Model\Exceptions\MissingMethodName

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\MissingModelClassName

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $paramKey );

Mvc\Model\Exceptions\ModelCouldNotLoad

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $modelName );

Mvc\Model\Exceptions\ModelOrmServicesUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $attribute,
    string $className
);

Mvc\Model\Exceptions\PrimaryKeyRequired

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\PropertyNotAccessible

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $property,
    string $className
);

Mvc\Model\Exceptions\RecordCannotRefresh

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\RecordNotPersisted

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\ReferencedFieldsMismatch

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $relationType,
    string $entityName,
    string $referencedEntity
);

Mvc\Model\Exceptions\RelationAliasMustBeString

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $relationType,
    string $entityName,
    string $referencedEntity
);

Mvc\Model\Exceptions\RelationNotDefined

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $className,
    string $alias
);

Mvc\Model\Exceptions\RelationRequiresObjectOrArray

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $className,
    string $relationName
);

Mvc\Model\Exceptions\ResultsetColumnNotInMap

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Model\Exceptions\RowIsImmutable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\SnapshotsDisabled

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\StaticMethodRequiresOneArgument

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $method,
    string $className
);

Mvc\Model\Exceptions\UnknownRelationType

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\UpdateSnapshotDisabled

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Hydration\CaseInsensitiveColumnMap

Class Source on GitHub

  • Phalcon\Mvc\Model\Hydration\CaseInsensitiveColumnMap

Method Summary

Methods

Public · 1

caseInsensitiveColumnMap()

public static function caseInsensitiveColumnMap(
    mixed $columnMap,
    mixed $key
): string;

Mvc\Model\Hydration\CloneResultMapHydrate

Class Source on GitHub

  • Phalcon\Mvc\Model\Hydration\CloneResultMapHydrate

Uses Phalcon\Mvc\Model\Exceptions\ColumnNotInMap · Phalcon\Mvc\Model\Resultset · Phalcon\Support\Settings

Method Summary

Methods

Public · 1

cloneResultMapHydrate()

public static function cloneResultMapHydrate(
    array $data,
    mixed $columnMap,
    int $hydrationMode,
    string $calledClass = "Phalcon\\Mvc\\Model"
);

Mvc\Model\Manager

Class Source on GitHub

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();
    }
);

$invoice = new Invoices($di);

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

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 registerWrite( ModelInterface $model ) Marks the model's write connection service as written-to for the public void removeBehavior(ModelInterface $model,string $behaviorClass) Removes a behavior from a model public void resetConnectionState() Clears the per-request sticky write tracking. Call this between 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 setSticky( bool $sticky ) Enables or disables sticky connections. When enabled, once a model has 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 $dirtyWriteServices = [] Write connection services that have been written to during the current request cycle. Used by the sticky mechanism to route reads to the write connection after a write.
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 bool $sticky = false Whether reads should stick to the write connection after a write has occurred during the current request cycle.
protected array $writeConnectionServices = []

Methods

Public · 73

__destruct()

public function __destruct();

Destroys the current PHQL cache

addBehavior()

public function addBehavior(
    ModelInterface $model,
    BehaviorInterface $behavior
): void;

Binds a behavior to a model

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()

public function addHasMany(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;

Setup a relation 1-n between two models

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()

public function addHasOne(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;

Setup a 1-1 relation between two models

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()

public function clearReusableObjects(): void;

Clears the internal reusable list

createBuilder()

public function createBuilder( mixed $params = null ): BuilderInterface;

Creates a Phalcon\Mvc\Model\Query\Builder

createQuery()

public function createQuery( string $phql ): QueryInterface;

Creates a Phalcon\Mvc\Model\Query without execute it

executeQuery()

public function executeQuery(
    string $phql,
    mixed $placeholders = null,
    mixed $types = null
): mixed;

Creates a Phalcon\Mvc\Model\Query and execute it

$model = new Invoices();
$manager = $model->getModelsManager();

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

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

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

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

// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('DELETE FROM Invoices WHERE inv_id = :id:', ['id' => 1]);

existsBelongsTo()

public function existsBelongsTo(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a belongsTo relation with another model

existsHasMany()

public function existsHasMany(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasMany relation with another model

existsHasManyToMany()

public function existsHasManyToMany(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasManyToMany relation with another model

existsHasOne()

public function existsHasOne(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasOne relation with another model

existsHasOneThrough()

public function existsHasOneThrough(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasOneThrough relation with another model

getBelongsTo()

public function getBelongsTo( ModelInterface $model ): RelationInterface[]|array;

Gets all the belongsTo relations defined in a model

$relations = $modelsManager->getBelongsTo(
    new Invoices()
);

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()

public function getBuilder(): BuilderInterface|null;

Returns the newly created Phalcon\Mvc\Model\Query\Builder or null

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()

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()

public function getDI(): DiInterface;

Returns the DependencyInjector container

getEventsManager()

public function getEventsManager(): EventsManagerInterface|null;

Returns the internal event manager

getHasMany()

public function getHasMany( ModelInterface $model ): RelationInterface[]|array;

Gets hasMany relations defined on a model

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()

public function getHasManyToMany( ModelInterface $model ): RelationInterface[]|array;

Gets hasManyToMany relations defined on a model

getHasOne()

public function getHasOne( ModelInterface $model ): array;

Gets hasOne relations defined on a model

getHasOneAndHasMany()

public function getHasOneAndHasMany( ModelInterface $model ): RelationInterface[];

Gets hasOne relations defined on a model

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()

public function getHasOneThrough( ModelInterface $model ): RelationInterface[]|array;

Gets hasOneThrough relations defined on a model

getLastInitialized()

public function getLastInitialized(): ModelInterface|null;

Get last initialized model

getLastQuery()

public function getLastQuery(): QueryInterface;

Returns the last query created or executed in the models manager

getModelPrefix()

public function getModelPrefix(): string;

Returns the prefix for all model sources.

getModelSchema()

public function getModelSchema( ModelInterface $model ): string|null;

Returns the mapped schema for a model

getModelSource()

public function getModelSource( ModelInterface $model ): string;

Returns the mapped source for a model

getReadConnection()

public function getReadConnection( ModelInterface $model ): AdapterInterface;

Returns the connection to read data related to a model

getReadConnectionService()

public function getReadConnectionService( ModelInterface $model ): string;

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

getRelationByAlias()

public function getRelationByAlias(
    string $modelName,
    string $alias
): RelationInterface|bool;

Returns a relation by its alias

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()

public function getRelations( string $modelName ): RelationInterface[];

Query all the relationships defined on a model

getRelationsBetween()

public function getRelationsBetween(
    string $first,
    string $second
): RelationInterface[]|bool;

Query the first relationship defined between two models

getReusableRecords()

public function getReusableRecords(
    string $modelName,
    string $key
);

Returns a reusable object from the internal list

getWriteConnection()

public function getWriteConnection( ModelInterface $model ): AdapterInterface;

Returns the connection to write data related to a model

getWriteConnectionService()

public function getWriteConnectionService( ModelInterface $model ): string;

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

hasBelongsTo()

public function hasBelongsTo(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a belongsTo relation with another model

hasHasMany()

public function hasHasMany(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasMany relation with another model

hasHasManyToMany()

public function hasHasManyToMany(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasManyToMany relation with another model

hasHasOne()

public function hasHasOne(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasOne relation with another model

hasHasOneThrough()

public function hasHasOneThrough(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasOneThrough relation with another model

initialize()

public function initialize( ModelInterface $model ): bool;

Initializes a model in the model manager

isInitialized()

public function isInitialized( string $className ): bool;

Check whether a model is already initialized

isKeepingSnapshots()

public function isKeepingSnapshots( ModelInterface $model ): bool;

Checks if a model is keeping snapshots for the queried records

isUsingDynamicUpdate()

public function isUsingDynamicUpdate( ModelInterface $model ): bool;

Checks if a model is using dynamic update instead of all-field update

isVisibleModelProperty()

final public function isVisibleModelProperty(
    ModelInterface $model,
    string $property
): bool;

Check whether a model property is declared as public.

$isPublic = $manager->isVisibleModelProperty(
    new Invoices(),
    "name"
);

keepSnapshots()

public function keepSnapshots(
    ModelInterface $model,
    bool $keepSnapshots
): void;

Sets if a model must keep snapshots

load()

public function load( string $modelName ): ModelInterface;

Loads a model throwing an exception if it does not exist

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()

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

registerWrite()

public function registerWrite( ModelInterface $model ): void;

Marks the model's write connection service as written-to for the current request cycle. Used by the sticky mechanism to route subsequent reads to the write connection.

removeBehavior()

public function removeBehavior(
    ModelInterface $model,
    string $behaviorClass
): void;

Removes a behavior from a model

resetConnectionState()

public function resetConnectionState(): void;

Clears the per-request sticky write tracking. Call this between requests in long-running runtimes (e.g. Swoole, RoadRunner) where the manager instance is reused across requests.

setConnectionService()

public function setConnectionService(
    ModelInterface $model,
    string $connectionService
): void;

Sets both write and read connection service for a model

setCustomEventsManager()

public function setCustomEventsManager(
    ModelInterface $model,
    EventsManagerInterface $eventsManager
): void;

Sets a custom events manager for a specific model

setDI()

public function setDI( DiInterface $container ): void;

Sets the DependencyInjector container

setEventsManager()

public function setEventsManager( EventsManagerInterface $eventsManager ): void;

Sets a global events manager

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;
    }
);

$invoices = new Invoices();

echo $invoices->getSource(); // wp_co_invoices

$param string $prefix

setModelSchema()

public function setModelSchema(
    ModelInterface $model,
    string $schema
): void;

Sets the mapped schema for a model

setModelSource()

public function setModelSource(
    ModelInterface $model,
    string $source
): void;

Sets the mapped source for a model

setReadConnectionService()

public function setReadConnectionService(
    ModelInterface $model,
    string $connectionService
): void;

Sets read connection service for a model

setReusableRecords()

public function setReusableRecords(
    string $modelName,
    string $key,
    mixed $records
): void;

Stores a reusable record in the internal list

setSticky()

public function setSticky( bool $sticky ): void;

Enables or disables sticky connections. When enabled, once a model has written to its write connection during the current request cycle, any further reads for that write service use the write connection.

setWriteConnectionService()

public function setWriteConnectionService(
    ModelInterface $model,
    string $connectionService
): void;

Sets write connection service for a model

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()

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()

final protected function mergeFindParameters(
    mixed $findParamsOne,
    mixed $findParamsTwo
): array;

Merge two arrays of find parameters

Mvc\Model\ManagerInterface

Interface Source on GitHub

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

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 registerWrite( ModelInterface $model ) Marks the model's write connection service as written-to for the public void removeBehavior(ModelInterface $model,string $behaviorClass) Removes a behavior from a model public void resetConnectionState() Clears the per-request sticky write tracking 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 void setSticky( bool $sticky ) Enables or disables sticky connections 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 · 58

addBehavior()

public function addBehavior(
    ModelInterface $model,
    BehaviorInterface $behavior
): void;

Binds a behavior to a model

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()

public function addHasMany(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;

Setup a relation 1-n between two models

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()

public function addHasOne(
    ModelInterface $model,
    mixed $fields,
    string $referencedModel,
    mixed $referencedFields,
    array $options = []
): RelationInterface;

Setup a 1-1 relation between two models

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()

public function clearReusableObjects(): void;

Clears the internal reusable list

createBuilder()

public function createBuilder( mixed $params = null ): BuilderInterface;

Creates a Phalcon\Mvc\Model\Query\Builder

createQuery()

public function createQuery( string $phql ): QueryInterface;

Creates a Phalcon\Mvc\Model\Query without execute it

executeQuery()

public function executeQuery(
    string $phql,
    mixed $placeholders = null,
    mixed $types = null
): mixed;

Creates a Phalcon\Mvc\Model\Query and execute it

getBelongsTo()

public function getBelongsTo( ModelInterface $model ): RelationInterface[]|array;

Gets belongsTo relations defined on a model

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()

public function getBuilder(): BuilderInterface|null;

Returns the newly created Phalcon\Mvc\Model\Query\Builder or null

getHasMany()

public function getHasMany( ModelInterface $model ): RelationInterface[]|array;

Gets hasMany relations defined on a model

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()

public function getHasManyToMany( ModelInterface $model ): RelationInterface[]|array;

Gets hasManyToMany relations defined on a model

getHasOne()

public function getHasOne( ModelInterface $model ): RelationInterface[]|array;

Gets hasOne relations defined on a model

getHasOneAndHasMany()

public function getHasOneAndHasMany( ModelInterface $model ): RelationInterface[];

Gets hasOne relations defined on a model

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()

public function getHasOneThrough( ModelInterface $model ): RelationInterface[]|array;

Gets hasOneThrough relations defined on a model

getLastInitialized()

public function getLastInitialized(): ModelInterface|null;

Get last initialized model

getLastQuery()

public function getLastQuery(): QueryInterface;

Returns the last query created or executed in the models manager

getModelSchema()

public function getModelSchema( ModelInterface $model ): string|null;

Returns the mapped schema for a model

getModelSource()

public function getModelSource( ModelInterface $model ): string;

Returns the mapped source for a model

getReadConnection()

public function getReadConnection( ModelInterface $model ): AdapterInterface;

Returns the connection to read data related to a model

getReadConnectionService()

public function getReadConnectionService( ModelInterface $model ): string;

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

getRelationByAlias()

public function getRelationByAlias(
    string $modelName,
    string $alias
): RelationInterface|bool;

Returns a relation by its alias

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()

public function getRelations( string $modelName ): RelationInterface[];

Query all the relationships defined on a model

getRelationsBetween()

public function getRelationsBetween(
    string $first,
    string $second
): RelationInterface[]|bool;

Query the relations between two models

getReusableRecords()

public function getReusableRecords(
    string $modelName,
    string $key
);

Returns a reusable object from the internal list

getWriteConnection()

public function getWriteConnection( ModelInterface $model ): AdapterInterface;

Returns the connection to write data related to a model

getWriteConnectionService()

public function getWriteConnectionService( ModelInterface $model ): string;

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

hasBelongsTo()

public function hasBelongsTo(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a belongsTo relation with another model

hasHasMany()

public function hasHasMany(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasMany relation with another model

hasHasManyToMany()

public function hasHasManyToMany(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasManyToMany relation with another model

hasHasOne()

public function hasHasOne(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasOne relation with another model

hasHasOneThrough()

public function hasHasOneThrough(
    string $modelName,
    string $modelRelation
): bool;

Checks whether a model has a hasOneThrough relation with another model

initialize()

public function initialize( ModelInterface $model );

Initializes a model in the model manager

isInitialized()

public function isInitialized( string $className ): bool;

Check of a model is already initialized

isKeepingSnapshots()

public function isKeepingSnapshots( ModelInterface $model ): bool;

Checks if a model is keeping snapshots for the queried records

isUsingDynamicUpdate()

public function isUsingDynamicUpdate( ModelInterface $model ): bool;

Checks if a model is using dynamic update instead of all-field update

isVisibleModelProperty()

public function isVisibleModelProperty(
    ModelInterface $model,
    string $property
): bool;

Check whether a model property is declared as public.

$isPublic = $manager->isVisibleModelProperty(
    new Invoices(),
    "name"
);

keepSnapshots()

public function keepSnapshots(
    ModelInterface $model,
    bool $keepSnapshots
): void;

Sets if a model must keep snapshots

load()

public function load( string $modelName ): ModelInterface;

Loads a model throwing an exception if it does not exist

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()

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

registerWrite()

public function registerWrite( ModelInterface $model ): void;

Marks the model's write connection service as written-to for the current request cycle (sticky connections)

removeBehavior()

public function removeBehavior(
    ModelInterface $model,
    string $behaviorClass
): void;

Removes a behavior from a model

resetConnectionState()

public function resetConnectionState(): void;

Clears the per-request sticky write tracking

setConnectionService()

public function setConnectionService(
    ModelInterface $model,
    string $connectionService
): void;

Sets both write and read connection service for a model

setModelSchema()

public function setModelSchema(
    ModelInterface $model,
    string $schema
): void;

Sets the mapped schema for a model

setModelSource()

public function setModelSource(
    ModelInterface $model,
    string $source
): void;

Sets the mapped source for a model

setReadConnectionService()

public function setReadConnectionService(
    ModelInterface $model,
    string $connectionService
): void;

Sets read connection service for a model

setReusableRecords()

public function setReusableRecords(
    string $modelName,
    string $key,
    mixed $records
): void;

Stores a reusable record in the internal list

setSticky()

public function setSticky( bool $sticky ): void;

Enables or disables sticky connections

setWriteConnectionService()

public function setWriteConnectionService(
    ModelInterface $model,
    string $connectionService
);

Sets write connection service for a model

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 Source on GitHub

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 Invoices()
);

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

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 · Phalcon\Traits\Support\Helper\Arr\GetTrait

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 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()

public function getAdapter(): CacheAdapterInterface|null;

Return the internal cache adapter

getAttributes()

public function getAttributes( ModelInterface $model ): array;

Returns table attributes names (fields)

print_r(
    $metaData->getAttributes(
        new Invoices()
    )
);

getAutomaticCreateAttributes()

public function getAutomaticCreateAttributes( ModelInterface $model ): array;

Returns attributes that must be ignored from the INSERT SQL generation

print_r(
    $metaData->getAutomaticCreateAttributes(
        new Invoices()
    )
);

getAutomaticUpdateAttributes()

public function getAutomaticUpdateAttributes( ModelInterface $model ): array;

Returns attributes that must be ignored from the UPDATE SQL generation

print_r(
    $metaData->getAutomaticUpdateAttributes(
        new Invoices()
    )
);

getBindTypes()

public function getBindTypes( ModelInterface $model ): array;

Returns attributes and their bind data types

print_r(
    $metaData->getBindTypes(
        new Invoices()
    )
);

getColumnMap()

public function getColumnMap( ModelInterface $model ): array|null;

Returns the column map if any

print_r(
    $metaData->getColumnMap(
        new Invoices()
    )
);

getColumnMapUniqueKey()

public final function getColumnMapUniqueKey( ModelInterface $model ): string|null;

Returns a ColumnMap Unique key for meta-data is created using className

getDI()

public function getDI(): DiInterface;

Returns the DependencyInjector container

getDataTypes()

public function getDataTypes( ModelInterface $model ): array;

Returns attributes and their data types

print_r(
    $metaData->getDataTypes(
        new Invoices()
    )
);

getDataTypesNumeric()

public function getDataTypesNumeric( ModelInterface $model ): array;

Returns attributes which types are numerical

print_r(
    $metaData->getDataTypesNumeric(
        new Invoices()
    )
);

getDefaultValues()

public function getDefaultValues( ModelInterface $model ): array;

Returns attributes (which have default values) and their default values

print_r(
    $metaData->getDefaultValues(
        new Invoices()
    )
);

getEmptyStringAttributes()

public function getEmptyStringAttributes( ModelInterface $model ): array;

Returns attributes allow empty strings

print_r(
    $metaData->getEmptyStringAttributes(
        new Invoices()
    )
);

getIdentityField()

public function getIdentityField( ModelInterface $model ): bool|string|null;

Returns the name of identity field (if one is present)

print_r(
    $metaData->getIdentityField(
        new Invoices()
    )
);

getMetaDataUniqueKey()

public final function getMetaDataUniqueKey( ModelInterface $model ): string|null;

Returns a MetaData Unique key for meta-data is created using className

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()

public function getNonPrimaryKeyAttributes( ModelInterface $model ): array;

Returns an array of fields which are not part of the primary key

print_r(
    $metaData->getNonPrimaryKeyAttributes(
        new Invoices()
    )
);

getNotNullAttributes()

public function getNotNullAttributes( ModelInterface $model ): array;

Returns an array of not null attributes

print_r(
    $metaData->getNotNullAttributes(
        new Invoices()
    )
);

getPrimaryKeyAttributes()

public function getPrimaryKeyAttributes( ModelInterface $model ): array;

Returns an array of fields which are part of the primary key

print_r(
    $metaData->getPrimaryKeyAttributes(
        new Invoices()
    )
);

getReverseColumnMap()

public function getReverseColumnMap( ModelInterface $model ): array|null;

Returns the reverse column map if any

print_r(
    $metaData->getReverseColumnMap(
        new Invoices()
    )
);

getStrategy()

public function getStrategy(): StrategyInterface;

Return the strategy to obtain the meta-data

hasAttribute()

public function hasAttribute(
    ModelInterface $model,
    string $attribute
): bool;

Check if a model has certain attribute

var_dump(
    $metaData->hasAttribute(
        new Invoices(),
        "name"
    )
);

isEmpty()

public function isEmpty(): bool;

Checks if the internal meta-data container is empty

var_dump(
    $metaData->isEmpty()
);

modelEquals()

public function modelEquals(
    ModelInterface $first,
    ModelInterface $other
): bool;

Compares if two models are the same in memory

read()

public function read( mixed $key ): array|null;

Reads metadata from the adapter

readColumnMap()

final public function readColumnMap( ModelInterface $model ): array|null;

Reads the ordered/reversed column map for certain model

print_r(
    $metaData->readColumnMap(
        new Invoices()
    )
);

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 Invoices(),
        MetaData::MODELS_REVERSE_COLUMN_MAP
    )
);

readMetaData()

final public function readMetaData( ModelInterface $model ): array|null;

Reads the complete meta-data for certain model

print_r(
    $metaData->readMetaData(
        new Invoices()
    )
);

readMetaDataIndex()

final public function readMetaDataIndex(
    ModelInterface $model,
    int $index
): array|string|null;

Reads meta-data for certain model

print_r(
    $metaData->readMetaDataIndex(
        new Invoices(),
        0
    )
);

reset()

public function reset(): void;

Resets internal meta-data in order to regenerate it

$metaData->reset();

setAutomaticCreateAttributes()

public function setAutomaticCreateAttributes(
    ModelInterface $model,
    array $attributes
): void;

Set the attributes that must be ignored from the INSERT SQL generation

$metaData->setAutomaticCreateAttributes(
    new Invoices(),
    [
        "created_at" => true,
    ]
);

setAutomaticUpdateAttributes()

public function setAutomaticUpdateAttributes(
    ModelInterface $model,
    array $attributes
): void;

Set the attributes that must be ignored from the UPDATE SQL generation

$metaData->setAutomaticUpdateAttributes(
    new Invoices(),
    [
        "modified_at" => true,
    ]
);

setDI()

public function setDI( DiInterface $container ): void;

Sets the DependencyInjector container

setEmptyStringAttributes()

public function setEmptyStringAttributes(
    ModelInterface $model,
    array $attributes
): void;

Set the attributes that allow empty string values

$metaData->setEmptyStringAttributes(
    new Invoices(),
    [
        "name" => true,
    ]
);

setStrategy()

public function setStrategy( StrategyInterface $strategy ): void;

Set the meta-data extraction strategy

write()

public function write(
    string $key,
    array $data
): void;

Writes the metadata to adapter

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 Invoices(),
        MetaData::MODELS_REVERSE_COLUMN_MAP,
        [
            "leName" => "name",
        ]
    )
);
Protected · 3

initialize()

final protected function initialize(
    ModelInterface $model,
    mixed $key,
    mixed $table,
    mixed $schema
);

Initialize old behaviour for compatability

initializeColumnMap()

final protected function initializeColumnMap(
    ModelInterface $model,
    mixed $key
): bool;

Initialize ColumnMap for a certain table

initializeMetaData()

final protected function initializeMetaData(
    ModelInterface $model,
    mixed $key
): bool;

Initialize the metadata for certain table

Mvc\Model\MetaDataInterface

Interface Source on GitHub

Phalcon\Mvc\Model\MetaDataInterface

Interface for Phalcon\Mvc\Model\MetaData

  • Phalcon\Mvc\Model\MetaDataInterface

Uses Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface

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()

public function getAttributes( ModelInterface $model ): array;

Returns table attributes names (fields)

getAutomaticCreateAttributes()

public function getAutomaticCreateAttributes( ModelInterface $model ): array;

Returns attributes that must be ignored from the INSERT SQL generation

getAutomaticUpdateAttributes()

public function getAutomaticUpdateAttributes( ModelInterface $model ): array;

Returns attributes that must be ignored from the UPDATE SQL generation

getBindTypes()

public function getBindTypes( ModelInterface $model ): array;

Returns attributes and their bind data types

getColumnMap()

public function getColumnMap( ModelInterface $model ): array|null;

Returns the column map if any

getDataTypes()

public function getDataTypes( ModelInterface $model ): array;

Returns attributes and their data types

getDataTypesNumeric()

public function getDataTypesNumeric( ModelInterface $model ): array;

Returns attributes which types are numerical

getDefaultValues()

public function getDefaultValues( ModelInterface $model ): array;

Returns attributes (which have default values) and their default values

getEmptyStringAttributes()

public function getEmptyStringAttributes( ModelInterface $model ): array;

Returns attributes allow empty strings

getIdentityField()

public function getIdentityField( ModelInterface $model ): bool|string|null;

Returns the name of identity field (if one is present)

getNonPrimaryKeyAttributes()

public function getNonPrimaryKeyAttributes( ModelInterface $model ): array;

Returns an array of fields which are not part of the primary key

getNotNullAttributes()

public function getNotNullAttributes( ModelInterface $model ): array;

Returns an array of not null attributes

getPrimaryKeyAttributes()

public function getPrimaryKeyAttributes( ModelInterface $model ): array;

Returns an array of fields which are part of the primary key

getReverseColumnMap()

public function getReverseColumnMap( ModelInterface $model ): array|null;

Returns the reverse column map if any

getStrategy()

public function getStrategy(): StrategyInterface;

Return the strategy to obtain the meta-data

hasAttribute()

public function hasAttribute(
    ModelInterface $model,
    string $attribute
): bool;

Check if a model has certain attribute

isEmpty()

public function isEmpty(): bool;

Checks if the internal meta-data container is empty

read()

public function read( string $key ): array|null;

Reads meta-data from the adapter

readColumnMap()

public function readColumnMap( ModelInterface $model ): array|null;

Reads the ordered/reversed column map for certain model

readColumnMapIndex()

public function readColumnMapIndex(
    ModelInterface $model,
    int $index
): array|null;

Reads column-map information for certain model using a MODEL_* constant

readMetaData()

public function readMetaData( ModelInterface $model ): array|null;

Reads meta-data for certain model

readMetaDataIndex()

public function readMetaDataIndex(
    ModelInterface $model,
    int $index
): array|string|null;

Reads meta-data for certain model using a MODEL_* constant

reset()

public function reset();

Resets internal meta-data in order to regenerate it

setAutomaticCreateAttributes()

public function setAutomaticCreateAttributes(
    ModelInterface $model,
    array $attributes
);

Set the attributes that must be ignored from the INSERT SQL generation

setAutomaticUpdateAttributes()

public function setAutomaticUpdateAttributes(
    ModelInterface $model,
    array $attributes
);

Set the attributes that must be ignored from the UPDATE SQL generation

setEmptyStringAttributes()

public function setEmptyStringAttributes(
    ModelInterface $model,
    array $attributes
): void;

Set the attributes that allow empty string values

setStrategy()

public function setStrategy( StrategyInterface $strategy );

Set the meta-data extraction strategy

write()

public function write(
    string $key,
    array $data
): void;

Writes meta-data to the adapter

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 Source on GitHub

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,
    ]
);

Uses Phalcon\Cache\AdapterFactory · Phalcon\Mvc\Model\MetaData

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    AdapterFactory $factory,
    array $options = null
);

Phalcon\Mvc\Model\MetaData\Apcu constructor

Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $completeTable,
    string $className
);

Mvc\Model\MetaData\Exceptions\ColumnMapNotArray

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\ContainerRequired

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\CorruptedMetaData

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\InvalidContainer

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $modelName );

Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $message );

Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\MetaData\Exceptions\TableNotInDatabase

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $completeTable,
    string $className
);

Mvc\Model\MetaData\Libmemcached

Class Source on GitHub

Phalcon\Mvc\Model\MetaData\Libmemcached

Stores model meta-data in the Memcache.

By default meta-data is stored for 48 hours (172800 seconds)

Uses Phalcon\Cache\AdapterFactory · Phalcon\Mvc\Model\MetaData

Method Summary

Methods

Public · 2

__construct()

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

Phalcon\Mvc\Model\MetaData\Libmemcached constructor

reset()

public function reset(): void;

Flush Memcache data and resets internal meta-data in order to regenerate it

Mvc\Model\MetaData\Memory

Class Source on GitHub

Phalcon\Mvc\Model\MetaData\Memory

Stores model meta-data in memory. Data will be erased when the request finishes

Uses Phalcon\Mvc\Model\MetaData

Method Summary

Methods

Public · 2

read()

public function read( mixed $key ): array|null;

Reads the meta-data from temporal memory

write()

public function write(
    mixed $key,
    array $data
): void;

Writes the meta-data to temporal memory

Mvc\Model\MetaData\Redis

Class Source on GitHub

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,
    ]
);

Uses Phalcon\Cache\AdapterFactory · Phalcon\Mvc\Model\MetaData

Method Summary

Methods

Public · 2

__construct()

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

Phalcon\Mvc\Model\MetaData\Redis constructor

reset()

public function reset(): void;

Flush Redis data and resets internal meta-data in order to regenerate it

Mvc\Model\MetaData\Strategy\Annotations

Class Source on GitHub

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

Method Summary

Methods

Public · 2

getColumnMaps()

final public function getColumnMaps(
    ModelInterface $model,
    DiInterface $container
): array;

Read the model's column map, this can't be inferred

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 Source on GitHub

Queries the table meta-data in order to introspect the model's metadata

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

Method Summary

Methods

Public · 2

getColumnMaps()

final public function getColumnMaps(
    ModelInterface $model,
    DiInterface $container
): array;

Read the model's column map, this can't be inferred

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 Source on GitHub

  • Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface

Uses Phalcon\Di\DiInterface · Phalcon\Mvc\ModelInterface

Method Summary

Methods

Public · 2

getColumnMaps()

public function getColumnMaps(
    ModelInterface $model,
    DiInterface $container
): array;

Read the model's column map, this can't be inferred

@todo Not implemented

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 Source on GitHub

Phalcon\Mvc\Model\MetaData\Stream

Stores model meta-data in PHP files.

$metaData = new \Phalcon\Mvc\Model\MetaData\Files(
    [
        "metaDataDir" => "app/cache/metadata/",
    ]
);

Uses Phalcon\Mvc\Model\MetaData · Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable · Phalcon\Support\Settings · Phalcon\Traits\Php\FileTrait

Method Summary

Properties

protected string $metaDataDir = "./"

Methods

Public · 3

__construct()

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

Phalcon\Mvc\Model\MetaData\Files constructor

read()

public function read( mixed $key ): array|null;

Reads meta-data from files

write()

public function write(
    mixed $key,
    array $data
): void;

Writes the meta-data to files

Mvc\Model\Query

Class Source on GitHub

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 Invoices';

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

$newInvoice = new Invoices();
$newInvoice->setTransaction($myTransaction);
$newInvoice->inv_status_flag = 1;
$newInvoice->inv_title = "Test Invoice";
$newInvoice->inv_total = 100;
$newInvoice->save();

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

$resultWithEntries = $queryWithTransaction->execute();

$queryWithOutTransaction = new Query($phql, $di);
$resultWithOutEntries = $queryWithTransaction->execute();

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\InvalidResultsetRowClass · 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\ResultsetRowClassNotFound · 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

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 string getResultsetRowClass() Returns the class that will be used to hydrate rows that are not mapped 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 setResultsetRowClass( string $resultsetRowClass ) Sets the class used to hydrate rows that are not mapped to a model 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 string $resultsetRowClass = ""
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 · 26

__construct()

public function __construct(
    string $phql = null,
    DiInterface $container = null,
    array $options = []
);

Phalcon\Mvc\Model\Query constructor

cache()

public function cache( array $cacheOptions ): QueryInterface;

Sets the cache parameters of the query

clean()

public static function clean(): void;

Destroys the internal PHQL cache

execute()

public function execute(
    array $bindParams = [],
    array $bindTypes = []
);

Executes a parsed PHQL statement

getBindParams()

public function getBindParams(): array;

Returns default bind params

getBindTypes()

public function getBindTypes(): array;

Returns default bind types

getCache()

public function getCache(): AdapterInterface;

Returns the current cache backend instance

getCacheOptions()

public function getCacheOptions(): array;

Returns the current cache options

getDI()

public function getDI(): DiInterface;

Returns the dependency injection container

getIntermediate()

public function getIntermediate(): array;

Returns the intermediate representation of the PHQL statement

getResultsetRowClass()

public function getResultsetRowClass(): string;

Returns the class that will be used to hydrate rows that are not mapped to a model (custom columns/joins). An empty string means the default Phalcon\Mvc\Model\Row is used.

getSingleResult()

public function getSingleResult(
    array $bindParams = [],
    array $bindTypes = []
): ModelInterface;

Executes the query returning the first result

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 co_invoices WHERE inv_cst_id = :cst_id',
    'bind' => ['cst_id' => 123],
    'bindTypes => ['cst_id' => 1] // 1 corresponds to int
]

getTransaction()

public function getTransaction(): TransactionInterface|null;

getType()

public function getType(): int;

Gets the type of PHQL statement executed

getUniqueRow()

public function getUniqueRow(): bool;

Check if the query is programmed to get only the first row in the resultset

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()

public function setBindParams(
    array $bindParams,
    bool $merge = false
): QueryInterface;

Set default bind parameters

setBindTypes()

public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): QueryInterface;

Set default bind parameters

setDI()

public function setDI( DiInterface $container ): void;

Sets the dependency injection container

setIntermediate()

public function setIntermediate( array $intermediate ): QueryInterface;

Allows to set the IR to be executed

setResultsetRowClass()

public function setResultsetRowClass( string $resultsetRowClass ): QueryInterface;

Sets the class used to hydrate rows that are not mapped to a model (custom columns/joins). The class must be a subclass of Phalcon\Mvc\Model\Row.

setSharedLock()

public function setSharedLock( bool $sharedLock = false ): QueryInterface;

Set SHARED LOCK clause

setTransaction()

public function setTransaction( TransactionInterface $transaction ): QueryInterface;

allows to wrap a transaction around all queries

setType()

public function setType( int $type ): QueryInterface;

Sets the type of PHQL statement to be executed

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()

final protected function executeDelete(
    array $intermediate,
    array $bindParams,
    array $bindTypes
): StatusInterface;

Executes the DELETE intermediate representation producing a Phalcon\Mvc\Model\Query\Status

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()

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()

final protected function executeUpdate(
    array $intermediate,
    array $bindParams,
    array $bindTypes
): StatusInterface;

Executes the UPDATE intermediate representation producing a Phalcon\Mvc\Model\Query\Status

getCallArgument()

final protected function getCallArgument( array $argument ): array;

Resolves an expression in a single call argument

getCaseExpression()

final protected function getCaseExpression( array $expr ): array;

Resolves an expression in a single call argument

getExpression()

final protected function getExpression(
    array $expr,
    bool $quoting = true
): array;

Resolves an expression from its intermediate code into an array

getFunctionCall()

final protected function getFunctionCall( array $expr ): array;

Resolves an expression in a single call argument

getGroupClause()

final protected function getGroupClause( array $group ): array;

Returns a processed group clause for a SELECT statement

getJoin()

final protected function getJoin(
    ManagerInterface $manager,
    array $join
): array;

Resolves a JOIN clause checking if the associated models exist

getJoinType()

final protected function getJoinType( array $join ): string;

Resolves a JOIN type

getJoins()

final protected function getJoins( array $select ): array;

Processes the JOINs in the query returning an internal representation for the database dialect

getLimitClause()

final protected function getLimitClause( array $limitClause ): array;

Returns a processed limit clause for a SELECT statement

getMultiJoin()

final protected function getMultiJoin(
    string $joinType,
    mixed $joinSource,
    string $modelAlias,
    string $joinAlias,
    RelationInterface $relation
): array;

Resolves joins involving many-to-many relations

getOrderClause()

final protected function getOrderClause( mixed $order ): array;

Returns a processed order clause for a SELECT statement

getQualified()

final protected function getQualified( array $expr ): array;

Replaces the model's name to its source name in a qualified-name expression

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()

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()

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()

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()

final protected function getTable(
    ManagerInterface $manager,
    array $qualifiedName
);

Resolves a table in a SELECT statement checking if the model exists

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()

final protected function prepareDelete(): array;

Analyzes a DELETE intermediate code and produces an array to be executed later

prepareInsert()

final protected function prepareInsert(): array;

Analyzes an INSERT intermediate code and produces an array to be executed later

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()

final protected function prepareUpdate(): array;

Analyzes an UPDATE intermediate code and produces an array to be executed later

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 Source on GitHub

Phalcon\Mvc\Model\QueryInterface

Interface for Phalcon\Mvc\Model\Query

  • Phalcon\Mvc\Model\QueryInterface

Uses Phalcon\Mvc\ModelInterface

Method Summary

Methods

Public · 13

cache()

public function cache( array $cacheOptions ): QueryInterface;

Sets the cache parameters of the query

execute()

public function execute(
    array $bindParams = [],
    array $bindTypes = []
);

Executes a parsed PHQL statement

getBindParams()

public function getBindParams(): array;

Returns default bind params

getBindTypes()

public function getBindTypes(): array;

Returns default bind types

getCacheOptions()

public function getCacheOptions(): array;

Returns the current cache options

getSingleResult()

public function getSingleResult(
    array $bindParams = [],
    array $bindTypes = []
): ModelInterface;

Executes the query returning the first result

getSql()

public function getSql(): array;

Returns the SQL to be generated by the internal PHQL (only works in SELECT statements)

getUniqueRow()

public function getUniqueRow(): bool;

Check if the query is programmed to get only the first row in the resultset

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()

public function setBindParams(
    array $bindParams,
    bool $merge = false
): QueryInterface;

Set default bind parameters

setBindTypes()

public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): QueryInterface;

Set default bind parameters

setSharedLock()

public function setSharedLock( bool $sharedLock = false ): QueryInterface;

Set SHARED LOCK clause

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 Source on GitHub

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);

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

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 string getResultsetRowClass() Returns the class that will be used to hydrate rows that are not mapped 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 setResultsetRowClass( string $resultsetRowClass ) Sets the class used to hydrate rows that are not mapped to a model 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 string $resultsetRowClass = ""
protected bool $sharedLock = false

Methods

Public · 50

__construct()

public function __construct(
    mixed $params = null,
    DiInterface $container = null
);

Phalcon\Mvc\Model\Query\Builder constructor

addFrom()

public function addFrom(
    string $model,
    string $alias = null
): BuilderInterface;

Add a model to take part of the query

// Load data from models Invoices
$builder->addFrom(
    Invoices::class
);

// Load data from model 'Invoices' using 'r' as alias in PHQL
$builder->addFrom(
    Invoices::class,
    "r"
);

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(Invoices.inv_total) > 0");

$builder->andHaving(
    "SUM(Invoices.inv_total) > :sum:",
    [
        "sum" => 100,
    ]
);

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()

final public function autoescape( string $identifier ): string;

Automatically escapes identifiers but only if they need to be escaped.

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(Invoices.inv_total)", 100.25, 200.50);

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()

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()

public function distinct( mixed $distinct ): BuilderInterface;

Sets SELECT DISTINCT / SELECT ALL flag

$builder->distinct("status");
$builder->distinct(null);

forUpdate()

public function forUpdate( bool $forUpdate ): BuilderInterface;

Sets a FOR UPDATE clause

$builder->forUpdate(true);

from()

public function from( mixed $models ): BuilderInterface;

Sets the models who makes part of the query

$builder->from(
    Invoices::class
);

$builder->from(
    [
        Invoices::class,
        OrdersProducts::class,
    ]
);

$builder->from(
    [
        "r"  => Invoices::class,
        "rp" => OrdersProducts::class,
    ]
);

getBindParams()

public function getBindParams(): array;

Returns default bind params

getBindTypes()

public function getBindTypes(): array;

Returns default bind types

getColumns()

public function getColumns();

Return the columns to be queried

getDI()

public function getDI(): DiInterface;

Returns the DependencyInjector container

getDistinct()

public function getDistinct(): bool;

Returns SELECT DISTINCT / SELECT ALL flag

getFrom()

public function getFrom();

Return the models who makes part of the query

getGroupBy()

public function getGroupBy(): array;

Returns the GROUP BY clause

getHaving()

public function getHaving(): string|null;

Return the current having clause

getJoins()

public function getJoins(): array;

Return join parts of the query

getLimit()

public function getLimit();

Returns the current LIMIT clause

getModels()

public function getModels(): string|array|null;

Returns the models involved in the query

getOffset()

public function getOffset(): int;

Returns the current OFFSET clause

getOrderBy()

public function getOrderBy();

Returns the set ORDER BY clause

getPhql()

final public function getPhql(): string;

Returns a PHQL statement built based on the builder parameters

getQuery()

public function getQuery(): QueryInterface;

Returns the query built

getResultsetRowClass()

public function getResultsetRowClass(): string;

Returns the class that will be used to hydrate rows that are not mapped to a model (custom columns/joins). An empty string means the default Phalcon\Mvc\Model\Row is used.

getWhere()

public function getWhere();

Return the conditions for the query

groupBy()

public function groupBy( mixed $group ): BuilderInterface;

Sets a GROUP BY clause

$builder->groupBy(
    [
        "Invoices.inv_title",
    ]
);

having()

public function having(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;

Sets the HAVING condition clause

$builder->having("SUM(Invoices.inv_total) > 0");

$builder->having(
    "SUM(Invoices.inv_total) > :sum:",
    [
        "sum" => 100,
    ]
);

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(Invoices.inv_total)", [100, 200]);

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()

public function innerJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;

Adds an INNER join to the query

// Inner Join model 'Invoices' with automatic conditions and alias
$builder->innerJoin(
    Invoices::class
);

// Inner Join model 'Invoices' specifying conditions
$builder->innerJoin(
    Invoices::class,
    "Invoices.inv_id = OrdersProducts.oxp_ord_id"
);

// Inner Join model 'Invoices' specifying conditions and alias
$builder->innerJoin(
    Invoices::class,
    "r.inv_id = OrdersProducts.oxp_ord_id",
    "r"
);

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 'Invoices' with automatic conditions and alias
$builder->join(
    Invoices::class
);

// Inner Join model 'Invoices' specifying conditions
$builder->join(
    Invoices::class,
    "Invoices.inv_id = OrdersProducts.oxp_ord_id"
);

// Inner Join model 'Invoices' specifying conditions and alias
$builder->join(
    Invoices::class,
    "r.inv_id = OrdersProducts.oxp_ord_id",
    "r"
);

// Left Join model 'Invoices' specifying conditions, alias and type of join
$builder->join(
    Invoices::class,
    "r.inv_id = OrdersProducts.oxp_ord_id",
    "r",
    "LEFT"
);

leftJoin()

public function leftJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;

Adds a LEFT join to the query

$builder->leftJoin(
    Invoices::class,
    "r.inv_id = OrdersProducts.oxp_ord_id",
    "r"
);

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()

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(Invoices.inv_total)", 100.25, 200.50);

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()

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(Invoices.inv_total)", [100, 200]);

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()

public function offset( int $offset ): BuilderInterface;

Sets an OFFSET clause

$builder->offset(30);

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(Invoices.inv_total) > 0");

$builder->orHaving(
    "SUM(Invoices.inv_total) > :sum:",
    [
        "sum" => 100,
    ]
);

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()

public function orderBy( mixed $orderBy ): BuilderInterface;

Sets an ORDER BY condition clause

$builder->orderBy("Invoices.inv_title");
$builder->orderBy(["1", "Invoices.inv_title"]);
$builder->orderBy(["Invoices.inv_title DESC"]);

rightJoin()

public function rightJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;

Adds a RIGHT join to the query

$builder->rightJoin(
    Invoices::class,
    "r.inv_id = OrdersProducts.oxp_ord_id",
    "r"
);

setBindParams()

public function setBindParams(
    array $bindParams,
    bool $merge = false
): BuilderInterface;

Set default bind parameters

setBindTypes()

public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): BuilderInterface;

Set default bind types

setDI()

public function setDI( DiInterface $container ): void;

Sets the DependencyInjector container

setResultsetRowClass()

public function setResultsetRowClass( string $resultsetRowClass ): BuilderInterface;

Sets the class used to hydrate rows that are not mapped to a model (custom columns/joins). The class must be a subclass of Phalcon\Mvc\Model\Row. Validation is performed by the underlying Phalcon\Mvc\Model\Query when the query is built.

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()

protected function conditionBetween(
    string $clause,
    string $operator,
    string $expr,
    mixed $minimum,
    mixed $maximum
): BuilderInterface;

Appends a BETWEEN condition

conditionIn()

protected function conditionIn(
    string $clause,
    string $operator,
    string $expr,
    array $values
): BuilderInterface;

Appends an IN condition

conditionNotBetween()

protected function conditionNotBetween(
    string $clause,
    string $operator,
    string $expr,
    mixed $minimum,
    mixed $maximum
): BuilderInterface;

Appends a NOT BETWEEN condition

conditionNotIn()

protected function conditionNotIn(
    string $clause,
    string $operator,
    string $expr,
    array $values
): BuilderInterface;

Appends a NOT IN condition

Mvc\Model\Query\BuilderInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\Model\Query\Builder

  • Phalcon\Mvc\Model\Query\BuilderInterface

Uses Phalcon\Mvc\Model\QueryInterface

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()

public function addFrom(
    string $model,
    string $alias = null
): BuilderInterface;

Add a model to take part of the query

andWhere()

public function andWhere(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;

Appends a condition to the current conditions using a AND operator

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()

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()

public function distinct( mixed $distinct ): BuilderInterface;

Sets SELECT DISTINCT / SELECT ALL flag

$builder->distinct("status");
$builder->distinct(null);

forUpdate()

public function forUpdate( bool $forUpdate ): BuilderInterface;

Sets a FOR UPDATE clause

$builder->forUpdate(true);

from()

public function from( mixed $models ): BuilderInterface;

Sets the models who makes part of the query

getBindParams()

public function getBindParams(): array;

Returns default bind params

getBindTypes()

public function getBindTypes(): array;

Returns default bind types

getColumns()

public function getColumns();

Return the columns to be queried

getDistinct()

public function getDistinct(): bool;

Returns SELECT DISTINCT / SELECT ALL flag

getFrom()

public function getFrom();

Return the models who makes part of the query

getGroupBy()

public function getGroupBy(): array;

Returns the GROUP BY clause

getHaving()

public function getHaving(): string|null;

Returns the HAVING condition clause

getJoins()

public function getJoins(): array;

Return join parts of the query

getLimit()

public function getLimit();

Returns the current LIMIT clause

getModels()

public function getModels(): string|array|null;

Returns the models involved in the query

getOffset()

public function getOffset(): int;

Returns the current OFFSET clause

getOrderBy()

public function getOrderBy();

Return the set ORDER BY clause

getPhql()

public function getPhql(): string;

Returns a PHQL statement built based on the builder parameters

getQuery()

public function getQuery(): QueryInterface;

Returns the query built

getWhere()

public function getWhere();

Return the conditions for the query

groupBy()

public function groupBy( mixed $group ): BuilderInterface;

Sets a GROUP BY clause

having()

public function having(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;

Sets a HAVING condition clause

inWhere()

public function inWhere(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;

Appends an IN condition to the current conditions

innerJoin()

public function innerJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;

Adds an INNER join to the query

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()

public function leftJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;

Adds a LEFT join to the query

limit()

public function limit(
    int $limit,
    mixed $offset = null
): BuilderInterface;

Sets a LIMIT clause

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()

public function notInWhere(
    string $expr,
    array $values,
    string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;

Appends a NOT IN condition to the current conditions

offset()

public function offset( int $offset ): BuilderInterface;

Sets an OFFSET clause

orWhere()

public function orWhere(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;

Appends a condition to the current conditions using an OR operator

orderBy()

public function orderBy( mixed $orderBy ): BuilderInterface;

Sets an ORDER BY condition clause

rightJoin()

public function rightJoin(
    string $model,
    string $conditions = null,
    string $alias = null
): BuilderInterface;

Adds a RIGHT join to the query

setBindParams()

public function setBindParams(
    array $bindParams,
    bool $merge = false
): BuilderInterface;

Set default bind parameters

setBindTypes()

public function setBindTypes(
    array $bindTypes,
    bool $merge = false
): BuilderInterface;

Set default bind types

where()

public function where(
    string $conditions,
    array $bindParams = [],
    array $bindTypes = []
): BuilderInterface;

Sets conditions for the query

Mvc\Model\Query\Exceptions\AmbiguousColumn

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $phql
);

Mvc\Model\Query\Exceptions\AmbiguousJoinRelation

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $from,
    string $join,
    string $phql
);

Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $wildcard );

Mvc\Model\Query\Exceptions\BindTypeRequiresArray

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Model\Query\Exceptions\BindValueRequired

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $column );

Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\Builder\ModelRequired

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $operator );

Mvc\Model\Query\Exceptions\ColumnNotInDomain

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $model,
    string $phql
);

Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $tag,
    string $phql
);

Mvc\Model\Query\Exceptions\CorruptedAst

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedDeleteAst

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedInsertAst

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedSelectAst

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedUpdateAst

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\DuplicateAlias

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $phql
);

Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Model\Query\Exceptions\InsertColumnCountMismatch

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidCachedResultset

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidCachingOptions

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidColumnDefinition

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidInjectedManager

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidInjectedMetadata

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidQueryCacheService

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidResultsetClass

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\InvalidResultsetRowClass

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $alias,
    string $phql
);

Mvc\Model\Query\Exceptions\JoinFieldCountMismatch

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $model,
    string $join,
    string $phql
);

Mvc\Model\Query\Exceptions\MissingCacheKey

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MissingMetaData

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MissingModelAttribute

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $model,
    string $attribute,
    string $phql
);

Mvc\Model\Query\Exceptions\MissingModelsManager

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MixedDatabaseSystems

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\ModelSourceNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $phql
);

Mvc\Model\Query\Exceptions\ModelsListNotLoaded

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\NoModelForAlias

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $model,
    string $phql
);

Mvc\Model\Query\Exceptions\PhqlColumnNotInMap

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $fieldName );

Mvc\Model\Query\Exceptions\ReadConnectionMissing

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\RelationshipNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $model,
    string $relationship,
    string $phql
);

Mvc\Model\Query\Exceptions\ResultsetClassNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\ResultsetNonCacheable

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\ResultsetRowClassNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\UnknownBindType

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UnknownColumnType

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UnknownJoinType

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $type,
    string $phql
);

Mvc\Model\Query\Exceptions\UnknownModelOrAlias

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $model,
    string $tag,
    string $phql
);

Mvc\Model\Query\Exceptions\UnknownPhqlExpression

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UnknownPhqlStatement

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\WriteConnectionMissing

Class Source on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Lang

Abstract Source on GitHub

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 Invoices r LIMIT 10"
);
  • Phalcon\Mvc\Model\Query\Lang

Method Summary

Methods

Public · 1

parsePHQL()

public static function parsePHQL( string $phql ): array;

Parses a PHQL statement returning an intermediate representation (IR)

Mvc\Model\Query\Status

Class Source on GitHub

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 Invoices SET inv_title = :inv_title:, inv_status_flag = :inv_status_flag:, inv_total = :inv_total: WHERE inv_id = :inv_id:";

$status = $app->modelsManager->executeQuery(
    $phql,
    [
        "inv_id"          => 100,
        "inv_title"       => "Test Invoice",
        "inv_status_flag" => 1,
        "inv_total"       => 1959,
    ]
);

// Check if the update was successful
if ($status->success()) {
    echo "OK";
}

Uses Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface

Method Summary

Properties

protected ModelInterface|null $model
protected bool $success

Methods

Public · 4

__construct()

public function __construct(
    bool $success,
    ModelInterface $model = null
);

Phalcon\Mvc\Model\Query\Status

getMessages()

public function getMessages(): MessageInterface[];

Returns the messages produced because of a failed operation

getModel()

public function getModel(): ModelInterface|null;

Returns the model that executed the action

success()

public function success(): bool;

Allows to check if the executed operation was successful

Mvc\Model\Query\StatusInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\Model\Query\Status

  • Phalcon\Mvc\Model\Query\StatusInterface

Uses Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface

Method Summary

Methods

Public · 3

getMessages()

public function getMessages(): MessageInterface[];

Returns the messages produced by an operation failed

getModel()

public function getModel(): ModelInterface|null;

Returns the model which executed the action

success()

public function success(): bool;

Allows to check if the executed operation was successful

Mvc\Model\Relation

Class Source on GitHub

Phalcon\Mvc\Model\Relation

This class represents a relationship between two models

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()

public function __construct(
    int $type,
    string $referencedModel,
    mixed $fields,
    mixed $referencedFields,
    array $options = []
);

Phalcon\Mvc\Model\Relation constructor

getFields()

public function getFields();

Returns the fields

getForeignKey()

public function getForeignKey();

Returns the foreign key configuration

getIntermediateFields()

public function getIntermediateFields();

Gets the intermediate fields for has-*-through relations

getIntermediateModel()

public function getIntermediateModel(): string;

Gets the intermediate model for has-*-through relations

getIntermediateReferencedFields()

public function getIntermediateReferencedFields();

Gets the intermediate referenced fields for has-*-through relations

getOption()

public function getOption( string $name );

Returns an option by the specified name If the option does not exist null is returned

getOptions()

public function getOptions(): array;

Returns the options

getParams()

public function getParams();

Returns parameters that must be always used when the related records are obtained

getReferencedFields()

public function getReferencedFields();

Returns the referenced fields

getReferencedModel()

public function getReferencedModel(): string;

Returns the referenced model

getType()

public function getType(): int;

Returns the relation type

isForeignKey()

public function isForeignKey(): bool;

Check whether the relation act as a foreign key

isReusable()

public function isReusable(): bool;

Check if records returned by getting belongs-to/has-many are implicitly cached during the current request

isThrough()

public function isThrough(): bool;

Check whether the relation is a 'many-to-many' relation or not

setIntermediateRelation()

public function setIntermediateRelation(
    mixed $intermediateFields,
    string $intermediateModel,
    mixed $intermediateReferencedFields
);

Sets the intermediate model data for has-*-through relations

Mvc\Model\RelationInterface

Interface Source on GitHub

Phalcon\Mvc\Model\RelationInterface

Interface for Phalcon\Mvc\Model\Relation

  • Phalcon\Mvc\Model\RelationInterface

Method Summary

Methods

Public · 15

getFields()

public function getFields();

Returns the fields

getForeignKey()

public function getForeignKey();

Returns the foreign key configuration

getIntermediateFields()

public function getIntermediateFields();

Gets the intermediate fields for has-*-through relations

getIntermediateModel()

public function getIntermediateModel(): string;

Gets the intermediate model for has-*-through relations

getIntermediateReferencedFields()

public function getIntermediateReferencedFields();

Gets the intermediate referenced fields for has-*-through relations

getOption()

public function getOption( string $name );

Returns an option by the specified name If the option does not exist null is returned

getOptions()

public function getOptions(): array;

Returns the options

getParams()

public function getParams();

Returns parameters that must be always used when the related records are obtained

getReferencedFields()

public function getReferencedFields();

Returns the referenced fields

getReferencedModel()

public function getReferencedModel(): string;

Returns the referenced model

getType()

public function getType(): int;

Returns the relations type

isForeignKey()

public function isForeignKey(): bool;

Check whether the relation act as a foreign key

isReusable()

public function isReusable(): bool;

Check if records returned by getting belongs-to/has-many are implicitly cached during the current request

isThrough()

public function isThrough(): bool;

Check whether the relation is a 'many-to-many' relation or not

setIntermediateRelation()

public function setIntermediateRelation(
    mixed $intermediateFields,
    string $intermediateModel,
    mixed $intermediateReferencedFields
);

Sets the intermediate model data for has-*-through relations

Mvc\Model\ResultInterface

Interface Source on GitHub

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

Method Summary

Methods

Public · 1

setDirtyState()

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

Sets the object's state

Mvc\Model\Resultset

Abstract Source on GitHub

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
$invoices = Invoices::find(
    [
        "inv_status_flag = 1",
        "order" => "inv_title",
    ]
);

foreach ($invoices as invoice) {
    echo invoice->inv_title, "\n";
}

// Using a while
$invoices = Invoices::find(
    [
        "inv_status_flag = 1",
        "order" => "inv_title",
    ]
);

$invoices->rewind();

while ($invoices->valid()) {
    $invoice = $invoices->current();

    echo $invoice->inv_title, "\n";

    $invoices->next();
}
@template TKey @template TValue @implements Iterator @implements ArrayAccess

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

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()

public function __construct(
    mixed $result,
    mixed $cache = null
);

Phalcon\Mvc\Model\Resultset constructor

count()

final public function count(): int;

Counts how many rows are in the resultset

delete()

public function delete( Closure $conditionCallback = null ): bool;

Deletes every record in the resultset

filter()

public function filter( callable $filter ): ModelInterface[];

Filters a resultset returning only those the developer requires

$filtered = $invoices->filter(
    function ($invoice) {
        if ($invoice->inv_id < 3) {
            return $invoice;
        }
    }
);

getCache()

public function getCache(): CacheInterface|null;

Returns the associated cache for the resultset

getFirst()

public function getFirst(): mixed|null;

Get first row in the resultset

$model = new Invoices();
$manager = $model->getModelsManager();

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

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

// NULL
$manager->createQuery('SELECT r.inv_id FROM Invoices AS r WHERE r.inv_title = "NON-EXISTENT"')
        ->execute()
        ->getFirst();

getHydrateMode()

public function getHydrateMode(): int;

Returns the current hydration mode

getLast()

public function getLast(): ModelInterface|null;

Get last row in the resultset

getMessages()

public function getMessages(): MessageInterface[];

Returns the error messages produced by a batch operation

getResult()

public function getResult(): mixed;

getType()

public function getType(): int;

Returns the internal type of data retrieval that the resultset is using

isFresh()

public function isFresh(): bool;

Tell if the resultset if fresh or an old one cached

jsonSerialize()

public function jsonSerialize(): array;

Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present

$invoices = Invoices::find();

echo json_encode($invoices);

key()

public function key(): int|null;

Gets pointer number of active row in the resultset

next()

public function next(): void;

Moves cursor to next row in the resultset

offsetExists()

public function offsetExists( mixed $index ): bool;

Checks whether offset exists in the resultset

offsetGet()

public function offsetGet( mixed $index ): mixed;

Gets row in a specific position of the resultset

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()

public function offsetUnset( mixed $offset ): void;

Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

refresh()

public function refresh(): bool;

rewind()

final public function rewind(): void;

Rewinds resultset to its beginning

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()

public function setHydrateMode( int $hydrateMode ): ResultsetInterface;

Sets the hydration mode in the resultset

setIsFresh()

public function setIsFresh( bool $isFresh ): ResultsetInterface;

Set if the resultset is fresh or an old one cached

update()

public function update(
    mixed $data,
    Closure $conditionCallback = null
): bool;

Updates every record in the resultset

valid()

public function valid(): bool;

Check whether internal resource has rows to fetch

Mvc\Model\ResultsetInterface

Interface Source on GitHub

Phalcon\Mvc\Model\ResultsetInterface

Interface for Phalcon\Mvc\Model\Resultset

  • Phalcon\Mvc\Model\ResultsetInterface

Uses Closure · Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface

Method Summary

Methods

Public · 13

delete()

public function delete( Closure $conditionCallback = null ): bool;

Deletes every record in the resultset

filter()

public function filter( callable $filter ): ModelInterface[];

Filters a resultset returning only those the developer requires

$filtered = $invoices->filter(
    function ($invoice) {
        if ($invoice->inv_id < 3) {
            return $invoice;
        }
    }
);

getCache()

public function getCache(): mixed|null;

Returns the associated cache for the resultset

getFirst()

public function getFirst(): mixed|null;

Get first row in the resultset

getHydrateMode()

public function getHydrateMode(): int;

Returns the current hydration mode

getLast()

public function getLast(): ModelInterface|null;

Get last row in the resultset

getMessages()

public function getMessages(): MessageInterface[];

Returns the error messages produced by a batch operation

getType()

public function getType(): int;

Returns the internal type of data retrieval that the resultset is using

isFresh()

public function isFresh(): bool;

Tell if the resultset if fresh or an old one cached

setHydrateMode()

public function setHydrateMode( int $hydrateMode ): ResultsetInterface;

Sets the hydration mode in the resultset

setIsFresh()

public function setIsFresh( bool $isFresh ): ResultsetInterface;

Set if the resultset is fresh or an old one cached

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()

public function update(
    mixed $data,
    Closure $conditionCallback = null
): bool;

Updates every record in the resultset

Mvc\Model\Resultset\Complex

Class Source on GitHub

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

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

Method Summary

Properties

protected array $columnTypes
protected bool $disableHydration = false Unserialised result-set hydrated all rows already. unserialise() sets disableHydration to true
protected string $resultsetRowClass = ""

Methods

Public · 7

__construct()

public function __construct(
    mixed $columnTypes,
    ResultInterface $result = null,
    mixed $cache = null,
    string $resultsetRowClass = ""
);

Phalcon\Mvc\Model\Resultset\Complex constructor

__serialize()

public function __serialize(): array;

__unserialize()

public function __unserialize( array $data ): void;

current()

final public function current(): mixed;

Returns current row in the resultset

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()

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()

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 Source on GitHub

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

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

Method Summary

Properties

protected array|string $columnMap
protected bool $keepSnapshots = false
protected ModelInterface|Row $model

Methods

Public · 7

__construct()

public function __construct(
    mixed $columnMap,
    mixed $model,
    mixed $result,
    mixed $cache = null,
    bool $keepSnapshots = false
);

Phalcon\Mvc\Model\Resultset\Simple constructor

__serialize()

public function __serialize(): array;

__unserialize()

public function __unserialize( array $data ): void;

current()

final public function current(): ModelInterface|Row|null;

Returns current row in the resultset

serialize()

public function serialize(): string;

Serializing a resultset will dump all related rows into a big array

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()

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 Source on GitHub

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].

Uses ArrayAccess · JsonSerializable · Phalcon\Mvc\EntityInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Exceptions\IndexNotInRow · Phalcon\Mvc\Model\Exceptions\RowIsImmutable

Method Summary

Methods

Public · 9

jsonSerialize()

public function jsonSerialize(): array;

Serializes the object for json_encode

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()

public function offsetGet( mixed $index ): mixed;

Gets a record in a specific position of the row

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()

public function offsetUnset( mixed $offset ): void;

Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface

readAttribute()

public function readAttribute( string $attribute );

Reads an attribute value by its name

echo $invoice->readAttribute("inv_title");

setDirtyState()

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

Set the current object's state

toArray()

public function toArray(): array;

Returns the instance as an array representation

writeAttribute()

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

Writes an attribute value by its name

$invoice->writeAttribute("inv_title", "Test Invoice");

Mvc\Model\Transaction

Class Source on GitHub

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();

    $invoice = new Invoices();

    $invoice->setTransaction($transaction);

    $invoice->inv_title    = "Test Invoice";
    $invoice->inv_created_at = date("Y-m-d");

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

    $product = new Products();

    $product->setTransaction($transaction);

    $product->prd_name = "Widget";

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

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

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

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()

public function __construct(
    DiInterface $container,
    bool $autoBegin = false,
    string $service = "db"
);

Phalcon\Mvc\Model\Transaction constructor

begin()

public function begin(): bool;

Starts the transaction

commit()

public function commit(): bool;

Commits the transaction

getConnection()

public function getConnection(): AdapterInterface;

Returns the connection related to transaction

getMessages()

public function getMessages(): array;

Returns validations messages from last save try

isManaged()

public function isManaged(): bool;

Checks whether transaction is managed by a transaction manager

isValid()

public function isValid(): bool;

Checks whether internal connection is under an active transaction

rollback()

public function rollback(
    string $rollbackMessage = null,
    ModelInterface $rollbackRecord = null
): bool;

Rollbacks the transaction

setIsNewTransaction()

public function setIsNewTransaction( bool $isNew ): void;

Sets if is a reused transaction or new once

setRollbackOnAbort()

public function setRollbackOnAbort( bool $rollbackOnAbort ): void;

Sets flag to rollback on abort the HTTP connection

setRollbackedRecord()

public function setRollbackedRecord( ModelInterface $record ): void;

Sets object which generates rollback action

setTransactionManager()

public function setTransactionManager( ManagerInterface $manager ): void;

Sets transaction manager related to the transaction

throwRollbackException()

public function throwRollbackException( bool $status ): TransactionInterface;

Enables throwing exception

Mvc\Model\TransactionInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\Model\Transaction

  • Phalcon\Mvc\Model\TransactionInterface

Uses Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Transaction\ManagerInterface

Method Summary

Methods

Public · 12

begin()

public function begin(): bool;

Starts the transaction

commit()

public function commit(): bool;

Commits the transaction

getConnection()

public function getConnection(): \Phalcon\Db\Adapter\AdapterInterface;

Returns connection related to transaction

getMessages()

public function getMessages(): array;

Returns validations messages from last save try

isManaged()

public function isManaged(): bool;

Checks whether transaction is managed by a transaction manager

isValid()

public function isValid(): bool;

Checks whether internal connection is under an active transaction

rollback()

public function rollback(
    string $rollbackMessage = null,
    ModelInterface $rollbackRecord = null
): bool;

Rollbacks the transaction

setIsNewTransaction()

public function setIsNewTransaction( bool $isNew ): void;

Sets if is a reused transaction or new once

setRollbackOnAbort()

public function setRollbackOnAbort( bool $rollbackOnAbort ): void;

Sets flag to rollback on abort the HTTP connection

setRollbackedRecord()

public function setRollbackedRecord( ModelInterface $record ): void;

Sets object which generates rollback action

setTransactionManager()

public function setTransactionManager( ManagerInterface $manager ): void;

Sets transaction manager related to the transaction

throwRollbackException()

public function throwRollbackException( bool $status ): TransactionInterface;

Enables throwing exception

Mvc\Model\Transaction\Exception

Class Source on GitHub

Phalcon\Mvc\Model\Transaction\Exception

Exceptions thrown in Phalcon\Mvc\Model\Transaction will use this class

Mvc\Model\Transaction\Failed

Class Source on GitHub

Phalcon\Mvc\Model\Transaction\Failed

This class will be thrown to exit a try/catch block for isolated transactions

Uses Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface

Method Summary

Properties

protected ModelInterface|null $record = null

Methods

Public · 3

__construct()

public function __construct(
    string $message,
    ModelInterface $record = null
);

Phalcon\Mvc\Model\Transaction\Failed constructor

getRecord()

public function getRecord(): ModelInterface|null;

Returns validation record messages which stop the transaction

getRecordMessages()

public function getRecordMessages(): array|string;

Returns validation record messages which stop the transaction

Mvc\Model\Transaction\Manager

Class Source on GitHub

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();

   $invoice = new Invoices();

   $invoice->setTransaction($transaction);

   $invoice->inv_title       = "Test Invoice";
   $invoice->inv_created_at = date("Y-m-d");

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

   $product = new Products();

   $product->setTransaction($transaction);

   $product->prd_name = "Widget";

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

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

Uses Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable · Phalcon\Mvc\Model\Transaction · Phalcon\Mvc\Model\TransactionInterface

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()

public function __construct( DiInterface $container = null );

Phalcon\Mvc\Model\Transaction\Manager constructor

collectTransactions()

public function collectTransactions(): void;

Remove all the transactions from the manager

commit()

public function commit();

Commits active transactions within the manager

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()

public function getDI(): DiInterface;

Returns the dependency injection container

getDbService()

public function getDbService(): string;

Returns the database service used to isolate the transaction

getOrCreateTransaction()

public function getOrCreateTransaction( bool $autoBegin = true ): TransactionInterface;

Create/Returns a new transaction or an existing one

getRollbackPendent()

public function getRollbackPendent(): bool;

Check if the transaction manager is registering a shutdown function to clean up pendent transactions

has()

public function has(): bool;

Checks whether the manager has an active transaction

notifyCommit()

public function notifyCommit( TransactionInterface $transaction ): void;

Notifies the manager about a committed transaction

notifyRollback()

public function notifyRollback( TransactionInterface $transaction ): void;

Notifies the manager about a rollbacked transaction

rollback()

public function rollback( bool $collect = true ): void;

Rollbacks active transactions within the manager Collect will remove the transaction from the manager

rollbackPendent()

public function rollbackPendent(): void;

Rollbacks active transactions within the manager

setDI()

public function setDI( DiInterface $container ): void;

Sets the dependency injection container

setDbService()

public function setDbService( string $service ): ManagerInterface;

Sets the database service used to run the isolated transactions

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()

protected function collectTransaction( TransactionInterface $transaction ): void;

Removes transactions from the TransactionManager

Mvc\Model\Transaction\ManagerInterface

Interface Source on GitHub

Phalcon\Mvc\Model\Transaction\ManagerInterface

Interface for Phalcon\Mvc\Model\Transaction\Manager

  • Phalcon\Mvc\Model\Transaction\ManagerInterface

Uses Phalcon\Mvc\Model\TransactionInterface

Method Summary

Methods

Public · 12

collectTransactions()

public function collectTransactions(): void;

Remove all the transactions from the manager

commit()

public function commit();

Commits active transactions within the manager

get()

public function get( bool $autoBegin = true ): TransactionInterface;

Returns a new \Phalcon\Mvc\Model\Transaction or an already created once

getDbService()

public function getDbService(): string;

Returns the database service used to isolate the transaction

getRollbackPendent()

public function getRollbackPendent(): bool;

Check if the transaction manager is registering a shutdown function to clean up pendent transactions

has()

public function has(): bool;

Checks whether manager has an active transaction

notifyCommit()

public function notifyCommit( TransactionInterface $transaction ): void;

Notifies the manager about a committed transaction

notifyRollback()

public function notifyRollback( TransactionInterface $transaction ): void;

Notifies the manager about a rollbacked transaction

rollback()

public function rollback( bool $collect = false ): void;

Rollbacks active transactions within the manager Collect will remove transaction from the manager

rollbackPendent()

public function rollbackPendent(): void;

Rollbacks active transactions within the manager

setDbService()

public function setDbService( string $service ): ManagerInterface;

Sets the database service used to run the isolated transactions

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 Source on GitHub

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

Uses Phalcon\Messages\Message · Phalcon\Mvc\ModelInterface

Method Summary

Properties

protected ModelInterface $model
protected array $validationMessages = []

Methods

Public · 3

__construct()

public function __construct(
    ModelInterface $model,
    array $validationMessages
);

Phalcon\Mvc\Model\ValidationFailed constructor

getMessages()

public function getMessages(): Message[];

Returns the complete group of messages produced in the validation

getModel()

public function getModel(): ModelInterface;

Returns the model that generated the messages

Mvc\ModuleDefinitionInterface

Interface Source on GitHub

This interface must be implemented by class module definitions

  • Phalcon\Mvc\ModuleDefinitionInterface

Uses Phalcon\Di\DiInterface

Method Summary

Methods

Public · 2

registerAutoloaders()

public function registerAutoloaders( DiInterface $container = null );

Registers an autoloader related to the module

registerServices()

public function registerServices( DiInterface $container );

Registers services related to the module

Mvc\Router

Class Source on GitHub

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();

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 · Phalcon\Traits\Php\FileTrait

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()

public function __construct( bool $defaultRoutes = true );

Phalcon\Mvc\Router constructor

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

public function clear(): void;

Removes all the pre-defined routes

dumpDispatcher()

public function dumpDispatcher( string $path ): void;

File-shaped helper around buildDispatcherDump(). Writes the dump as a <?php return [...]; file, atomically (temp + rename) so concurrent dumps don't corrupt the result.

getActionName()

public function getActionName(): string;

Returns the processed action name

getControllerName()

public function getControllerName(): string;

Returns the processed controller name

getDefaults()

public function getDefaults(): array;

Returns an array of default parameters

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

getKeyRouteIds()

public function getKeyRouteIds(): array;

getKeyRouteNames()

public function getKeyRouteNames(): array;

getMatchedRoute()

public function getMatchedRoute(): RouteInterface|null;

Returns the route that matches the handled URI

getMatches()

public function getMatches(): array;

Returns the sub expressions in the regular expression matched

getMethodRoutes()

public function getMethodRoutes(): array;

Returns the routes indexed by HTTP method. Routes with no HTTP constraint are stored under the "*" key.

getModuleName()

public function getModuleName(): string;

Returns the processed module name

getNamespaceName()

public function getNamespaceName(): string;

Returns the processed namespace name

getParams()

public function getParams(): array;

Returns the processed parameters

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()

public function getRouteById( mixed $routeId ): RouteInterface|bool;

Returns a route object by its id

getRouteByName()

public function getRouteByName( string $name ): RouteInterface|bool;

Returns a route object by its name

getRoutes()

public function getRoutes(): RouteInterface[];

Returns all the routes defined in the router

handle()

public function handle( string $uri ): void;

Handles routing information received from the rewrite engine

// Passing a URL
$router->handle("/posts/edit/1");

isExactControllerName()

public function isExactControllerName(): bool;

Returns whether controller name should not be mangled

loadDispatcher()

public function loadDispatcher( string $path ): void;

File-shaped helper around loadDispatcherFromArray(). Includes the file (opcache-friendly) and forwards the return value.

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()

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()

public function mount( GroupInterface $group ): static;

Mounts a group of routes in the router

notFound()

public function notFound( mixed $paths ): static;

Set a group of paths to be returned when none of the defined routes are matched

removeExtraSlashes()

public function removeExtraSlashes( bool $remove ): static;

Set whether router must remove the extra slashes in the handled routes

setDefaultAction()

public function setDefaultAction( string $actionName ): static;

Sets the default action name

setDefaultController()

public function setDefaultController( string $controllerName ): static;

Sets the default controller name

setDefaultModule()

public function setDefaultModule( string $moduleName ): static;

Sets the name of the default module

setDefaultNamespace()

public function setDefaultNamespace( string $namespaceName ): static;

Sets the name of the default namespace

@parma string namespaceName

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()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

setKeyRouteIds()

public function setKeyRouteIds( array $routeIds ): static;

setKeyRouteNames()

public function setKeyRouteNames( array $routeNames ): static;

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()

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()

public function wasMatched(): bool;

Checks if the router matches any of the defined routes

Protected · 4

addRouteFromConfig()

protected function addRouteFromConfig( array $routeData ): void;

Adds a single route from a config array entry. Used by loadFromConfig.

extractRealUri()

protected function extractRealUri( string $uri ): string;

mountGroupFromConfig()

protected function mountGroupFromConfig( array $groupData ): void;

Builds a Group from a config entry and mounts it. Used by loadFromConfig.

rebuildMethodIndex()

protected function rebuildMethodIndex(): void;

Mvc\RouterInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\Router

  • Phalcon\Mvc\RouterInterface

Uses Phalcon\Mvc\Router\GroupInterface · Phalcon\Mvc\Router\RouteInterface

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

public function attach(
    RouteInterface $route,
    int $position = Router::POSITION_LAST
): RouterInterface;

Attach Route object to the routes stack.

clear()

public function clear(): void;

Removes all the defined routes

getActionName()

public function getActionName(): string;

Returns processed action name

getControllerName()

public function getControllerName(): string;

Returns processed controller name

getMatchedRoute()

public function getMatchedRoute(): RouteInterface|null;

Returns the route that matches the handled URI

getMatches()

public function getMatches(): array;

Return the sub expressions in the regular expression matched

getModuleName()

public function getModuleName(): string;

Returns processed module name

getNamespaceName()

public function getNamespaceName(): string;

Returns processed namespace name

getParams()

public function getParams(): array;

Returns processed extra params

getRouteById()

public function getRouteById( mixed $routeId ): RouteInterface|bool;

Returns a route object by its id

getRouteByName()

public function getRouteByName( string $name ): RouteInterface|bool;

Returns a route object by its name

getRoutes()

public function getRoutes(): RouteInterface[];

Return all the routes defined in the router

handle()

public function handle( string $uri ): void;

Handles routing information received from the rewrite engine

loadFromConfig()

public function loadFromConfig( mixed $config ): RouterInterface;

Loads routes from an array or Phalcon\Config\Config instance.

mount()

public function mount( GroupInterface $group ): RouterInterface;

Mounts a group of routes in the router

setDefaultAction()

public function setDefaultAction( string $actionName ): RouterInterface;

Sets the default action name

setDefaultController()

public function setDefaultController( string $controllerName ): RouterInterface;

Sets the default controller name

setDefaultModule()

public function setDefaultModule( string $moduleName ): RouterInterface;

Sets the name of the default module

setDefaults()

public function setDefaults( array $defaults ): RouterInterface;

Sets an array of default paths

wasMatched()

public function wasMatched(): bool;

Check if the router matches any of the defined routes

Mvc\Router\Annotations

Class Source on GitHub

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 /invoices
        $router->addResource("Invoices", "/invoices");

        return $router;
    }
);

Uses Phalcon\Annotations\Annotation · Phalcon\Di\DiInterface · Phalcon\Mvc\Router · Phalcon\Mvc\Router\Exceptions\AnnotationsServiceUnavailable · Phalcon\Mvc\Router\Exceptions\InvalidCallbackParameter

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()

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()

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()

public function getActionPreformatCallback();

getResources()

public function getResources(): array;

Return the registered resources

handle()

public function handle( string $uri ): void;

Produce the routing parameters from the rewrite information

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()

public function processControllerAnnotation(
    string $handler,
    Annotation $annotation
);

Checks for annotations in the controller docblock

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()

public function setActionSuffix( string $actionSuffix ): self;

Changes the action method suffix

setControllerSuffix()

public function setControllerSuffix( string $controllerSuffix ): self;

Changes the controller class suffix

Mvc\Router\Exception

Class Source on GitHub

Phalcon\Mvc\Router\Exception

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

Mvc\Router\Exceptions\AnnotationsServiceUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\BeforeMatchNotCallable

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\ConfigKeyMustBeArray

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Router\Exceptions\EmptyGroupOfRoutes

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\GroupRoutesMustBeArray

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidCallbackParameter

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidConfigSource

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidNotFoundPaths

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidRoutePaths

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidRoutePosition

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidRouterFactoryConfig

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\MissingGroupRouteKey

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Router\Exceptions\MissingRouteConfigKey

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Router\Exceptions\RequestServiceUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\UnknownHttpMethod

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $method );

Mvc\Router\Exceptions\WrongPathsKey

Class Source on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $part );

Mvc\Router\Group

Class Source on GitHub

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);

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()

public function __construct( mixed $paths = null );

Phalcon\Mvc\Router\Group constructor

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

public function clear(): void;

Removes all the pre-defined routes

getBeforeMatch()

public function getBeforeMatch(): callable|null;

Returns the 'before match' callback if any

getHostname()

public function getHostname(): string|null;

Returns the hostname restriction

getPaths()

public function getPaths(): array|string|null;

Returns the common paths defined for this group

getPrefix()

public function getPrefix(): string|null;

Returns the common prefix for all the routes

getRoutes()

public function getRoutes(): RouteInterface[];

Returns the routes added to the group

setHostname()

public function setHostname( string $hostname ): GroupInterface;

Set a hostname restriction for all the routes in the group

setPaths()

public function setPaths( mixed $paths ): GroupInterface;

Set common paths for all the routes in the group

setPrefix()

public function setPrefix( string $prefix ): GroupInterface;

Set a common uri prefix for all the routes in this group

Protected · 1

addRoute()

protected function addRoute(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null
): RouteInterface;

Adds a route applying the common attributes

Mvc\Router\GroupInterface

Interface Source on GitHub

$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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

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()

public function clear(): void;

Removes all the pre-defined routes

getBeforeMatch()

public function getBeforeMatch(): callable|null;

Returns the 'before match' callback if any

getHostname()

public function getHostname(): string|null;

Returns the hostname restriction

getPaths()

public function getPaths(): array|string|null;

Returns the common paths defined for this group

getPrefix()

public function getPrefix(): string|null;

Returns the common prefix for all the routes

getRoutes()

public function getRoutes(): RouteInterface[];

Returns the routes added to the group

setHostname()

public function setHostname( string $hostname ): GroupInterface;

Set a hostname restriction for all the routes in the group

setPaths()

public function setPaths( mixed $paths ): GroupInterface;

Set common paths for all the routes in the group

setPrefix()

public function setPrefix( string $prefix ): GroupInterface;

Set a common uri prefix for all the routes in this group

Mvc\Router\Route

Class Source on GitHub

This class represents every route added to the router

Uses Phalcon\Mvc\Router\Exceptions\InvalidRoutePaths

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()

public function __construct(
    string $pattern,
    mixed $paths = null,
    mixed $httpMethods = null
);

Phalcon\Mvc\Router\Route constructor

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()

public function compilePattern( string $pattern ): string;

Replaces placeholders from pattern returning a valid PCRE regular expression

convert()

public function convert(
    string $name,
    mixed $converter
): RouteInterface;

{@inheritdoc}

extractNamedParams()

public function extractNamedParams( string $pattern ): array|bool;

Extracts parameters from a string

getBeforeMatch()

public function getBeforeMatch(): callable|null;

Returns the 'before match' callback if any

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()

public function getCompiledPattern(): string;

Returns the route's compiled pattern

getConverters()

public function getConverters(): array;

Returns the router converter

getGroup()

public function getGroup(): GroupInterface|null;

Returns the group associated with the route

getHostname()

public function getHostname(): string|null;

Returns the hostname restriction if any

getHttpMethods()

public function getHttpMethods(): array|string|null;

Returns the HTTP methods that constraint matching the route

getMatch()

public function getMatch(): callable|null;

Returns the 'match' callback if any

getName()

public function getName(): string|null;

Returns the route's name

getPaths()

public function getPaths(): array;

Returns the paths

getPattern()

public function getPattern(): string;

Returns the route's pattern

getReversedPaths()

public function getReversedPaths(): array;

Returns the paths using positions as keys and names as values

getRouteId()

public function getRouteId(): string;

Returns the route's id

getRoutePaths()

public static function getRoutePaths( mixed $paths = null ): array;

Returns routePaths

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()

public function reConfigure(
    string $pattern,
    mixed $paths = null
): void;

Reconfigure the route adding a new pattern and a set of paths

reset()

public static function reset(): void;

Resets the internal route id generator

setGroup()

public function setGroup( GroupInterface $group ): RouteInterface;

Sets the group associated with the route

setHostname()

public function setHostname( string $hostname ): RouteInterface;

Sets a hostname restriction to the route

$route->setHostname("localhost");

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()

public function setName( string $name ): RouteInterface;

Sets the route's name

$router->add(
    "/about",
    [
        "controller" => "about",
    ]
)->setName("about");

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()

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 Source on GitHub

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()

public function compilePattern( string $pattern ): string;

Replaces placeholders from pattern returning a valid PCRE regular expression

convert()

public function convert(
    string $name,
    mixed $converter
): RouteInterface;

Adds a converter to perform an additional transformation for certain parameter.

getCompiledPattern()

public function getCompiledPattern(): string;

Returns the route's pattern

getHostname()

public function getHostname(): string|null;

Returns the hostname restriction if any

getHttpMethods()

public function getHttpMethods(): array|string|null;

Returns the HTTP methods that constraint matching the route

getName()

public function getName(): string|null;

Returns the route's name

getPaths()

public function getPaths(): array;

Returns the paths

getPattern()

public function getPattern(): string;

Returns the route's pattern

getReversedPaths()

public function getReversedPaths(): array;

Returns the paths using positions as keys and names as values

getRouteId()

public function getRouteId(): string;

Returns the route's id

reConfigure()

public function reConfigure(
    string $pattern,
    mixed $paths = null
): void;

Reconfigure the route adding a new pattern and a set of paths

reset()

public static function reset(): void;

Resets the internal route id generator

setHostname()

public function setHostname( string $hostname ): RouteInterface;

Sets a hostname restriction to the route

setHttpMethods()

public function setHttpMethods( mixed $httpMethods ): RouteInterface;

Sets a set of HTTP methods that constraint the matching of the route

setName()

public function setName( string $name ): RouteInterface;

Sets the route's name

setRouteId()

public function setRouteId( string $routeId ): RouteInterface;

Sets the route's id (intended for restoring cached routes)

via()

public function via( mixed $httpMethods ): RouteInterface;

Set one or more HTTP methods that constraint the matching of the route

Mvc\Router\RouterFactory

Class Source on GitHub

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

Method Summary

Methods

Public · 2

load()

public function load( mixed $config ): RouterInterface;

Builds a Router from a config array or ConfigInterface and loads routes.

newInstance()

public function newInstance( bool $defaultRoutes = true ): RouterInterface;

Returns a bare Router instance.

Mvc\Url

Class Source on GitHub

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",
    ]
);

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 · Phalcon\Support\Helper\Str\ReduceSlashes

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()

public function __construct( RouterInterface $router = null );

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()

public function getBasePath(): string|null;

Returns the base path

getBaseUri()

public function getBaseUri(): string;

Returns the prefix for all the generated urls. By default /

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()

public function getStaticBaseUri(): string;

Returns the prefix for all the generated static urls. By default /

path()

public function path( string $path = null ): string;

Generates a local path

setBasePath()

public function setBasePath( string $basePath ): UrlInterface;

Sets a base path for all the generated paths

$url->setBasePath("/var/www/htdocs/");

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()

public function setStaticBaseUri( string $staticBaseUri ): UrlInterface;

Sets a prefix for all static URLs generated

$url->setStaticBaseUri("/invo/");

Mvc\Url\Exception

Class Source on GitHub

Phalcon\Mvc\Url\Exception

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

Mvc\Url\Exceptions\MissingRouteName

Class Source on GitHub

Uses Phalcon\Mvc\Url\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Url\Exceptions\RouteNotFound

Class Source on GitHub

Uses Phalcon\Mvc\Url\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Url\Exceptions\RouterServiceUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\Url\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Url\UrlInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\Url\UrlInterface

  • Phalcon\Mvc\Url\UrlInterface

Method Summary

Methods

Public · 6

get()

public function get(
    mixed $uri = null,
    mixed $arguments = null,
    bool $local = null,
    mixed $baseUri = null,
    bool $replaceArgs = false
): string;

Generates a URL

getBasePath()

public function getBasePath(): string|null;

Returns a base path

getBaseUri()

public function getBaseUri(): string;

Returns the prefix for all the generated urls. By default /

path()

public function path( string $path = null ): string;

Generates a local path

setBasePath()

public function setBasePath( string $basePath ): UrlInterface;

Sets a base paths for all the generated paths

setBaseUri()

public function setBaseUri( string $baseUri ): UrlInterface;

Sets a prefix to all the urls generated

Mvc\View

Class Source on GitHub

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();

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 · Phalcon\Mvc\View\Traits\ViewParamsTrait · Phalcon\Traits\Php\FileTrait · Phalcon\Traits\Support\Helper\Str\DirSeparatorTrait

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 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 string getPartial(string $partialPath,mixed $params = null) Renders a partial view public string getPartialsDir() Gets the current partials sub-directory 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 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 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 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 $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 int $renderLevel = 5
protected array $templatesAfter = []
protected array $templatesBefore = []
protected array $viewsDirs = []

Methods

Public · 47

__construct()

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

Phalcon\Mvc\View constructor

__get()

public function __get( string $key ): mixed|null;

Magic method to retrieve a variable passed to the view

echo $this->view->products;

__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()

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

Magic method to pass variables to the views

$this->view->products = $products;

cleanTemplateAfter()

public function cleanTemplateAfter(): static;

Resets any template before layouts

cleanTemplateBefore()

public function cleanTemplateBefore(): static;

Resets any "template before" layouts

disable()

public function disable(): static;

Disables the auto-rendering process

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()

public function enable(): static;

Enables the auto-rendering process

exists()

public function exists( string $view ): bool;

Checks whether view exists

finish()

public function finish(): static;

Finishes the render process by stopping the output buffering

getActionName()

public function getActionName(): string;

Gets the name of the action rendered

getActiveRenderPath()

public function getActiveRenderPath(): string|array;

Returns the path (or paths) of the views that are currently rendered

getBasePath()

public function getBasePath(): string;

Gets base path

getControllerName()

public function getControllerName(): string;

Gets the name of the controller rendered

getCurrentRenderLevel()

public function getCurrentRenderLevel(): int;

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

getLayout()

public function getLayout(): string|null;

Returns the name of the main view

getLayoutsDir()

public function getLayoutsDir(): string;

Gets the current layouts sub-directory

getMainView()

public function getMainView(): string;

Returns the name of the main view

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()

public function getPartialsDir(): string;

Gets the current partials sub-directory

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()

public function getRenderLevel(): int;

getViewsDir()

public function getViewsDir(): string|array;

Gets views directory

has()

public function has( string $view ): bool;

Checks whether view exists

isDisabled()

public function isDisabled(): bool;

Whether automatic rendering is enabled

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()

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()

public function processRender(
    string $controllerName,
    string $actionName,
    array $params = [],
    bool $fireEvents = true
): bool;

Processes the view and templates; Fires events if needed

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()

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()

public function reset(): static;

Resets the view component to its factory default values

setBasePath()

public function setBasePath( string $basePath ): static;

Sets base path. Depending of your platform, always add a trailing slash or backslash

$view->setBasePath(__DIR__ . "/");

setEventsManager()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

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()

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()

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()

public function setParamToView(
    string $key,
    mixed $value
): static;

Adds parameters to views (alias of setVar)

$this->view->setParamToView("products", $products);

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()

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()

public function setTemplateAfter( mixed $templateAfter ): static;

Sets a "template after" controller layout

setTemplateBefore()

public function setTemplateBefore( mixed $templateBefore ): static;

Sets a template before the controller layout

setVars()

public function setVars(
    array $params,
    bool $merge = true
): static;

Set all the render params

$this->view->setVars(
    [
        "products" => $products,
    ]
);

setViewsDir()

public function setViewsDir( mixed $viewsDir ): static;

Sets the views directory. Depending of your platform, always add a trailing slash or backslash

start()

public function start(): static;

Starts rendering process enabling the output buffering

toString()

public function toString(
    string $controllerName,
    string $actionName,
    array $params = []
): string;

Renders the view and returns it as a string

Protected · 4

engineRender()

protected function engineRender(
    array $engines,
    string $viewPath,
    bool $silence,
    bool $mustClean = true
);

Checks whether view exists on registered extensions and render it

getViewsDirs()

protected function getViewsDirs(): array;

Gets views directories

isAbsolutePath()

final protected function isAbsolutePath( string $path );

Checks if a path is absolute or not

loadTemplateEngines()

protected function loadTemplateEngines(): array;

Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php

Mvc\ViewBaseInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\View and Phalcon\Mvc\View\Simple

Uses Phalcon\Cache\Adapter\AdapterInterface

Method Summary

Methods

Public · 8

getContent()

public function getContent(): string;

Returns cached output from another view stage

getParamsToView()

public function getParamsToView(): array;

Returns parameters to views

getViewsDir()

public function getViewsDir(): string|array;

Gets views directory

partial()

public function partial(
    string $partialPath,
    mixed $params = null
);

Renders a partial view

setContent()

public function setContent( string $content );

Externally sets the view content

setParamToView()

public function setParamToView(
    string $key,
    mixed $value
);

Adds parameters to views (alias of setVar)

setVar()

public function setVar(
    string $key,
    mixed $value
);

Adds parameters to views

setViewsDir()

public function setViewsDir( string $viewsDir );

Sets views directory. Depending of your platform, always add a trailing slash or backslash

Mvc\ViewInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\View

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()

public function cleanTemplateAfter();

Resets any template before layouts

cleanTemplateBefore()

public function cleanTemplateBefore();

Resets any template before layouts

disable()

public function disable();

Disables the auto-rendering process

enable()

public function enable();

Enables the auto-rendering process

finish()

public function finish();

Finishes the render process by stopping the output buffering

getActionName()

public function getActionName(): string;

Gets the name of the action rendered

getActiveRenderPath()

public function getActiveRenderPath(): string|array;

Returns the path of the view that is currently rendered

getBasePath()

public function getBasePath(): string;

Gets base path

getControllerName()

public function getControllerName(): string;

Gets the name of the controller rendered

getLayout()

public function getLayout(): string|null;

Returns the name of the main view

getLayoutsDir()

public function getLayoutsDir(): string;

Gets the current layouts sub-directory

getMainView()

public function getMainView(): string;

Returns the name of the main view

getPartialsDir()

public function getPartialsDir(): string;

Gets the current partials sub-directory

isDisabled()

public function isDisabled(): bool;

Whether the automatic rendering is disabled

pick()

public function pick( string $renderView );

Choose a view different to render than last-controller/last-action

registerEngines()

public function registerEngines( array $engines );

Register templating engines

render()

public function render(
    string $controllerName,
    string $actionName,
    array $params = []
): ViewInterface|bool;

Executes render process from dispatching data

reset()

public function reset();

Resets the view component to its factory default values

setBasePath()

public function setBasePath( string $basePath );

Sets base path. Depending of your platform, always add a trailing slash or backslash

setLayout()

public function setLayout( string $layout );

Change the layout to be used instead of using the name of the latest controller name

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()

public function setMainView( string $viewPath );

Sets default view name. Must be a file without extension in the views directory

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()

public function setRenderLevel( int $level ): ViewInterface;

Sets the render level for the view

setTemplateAfter()

public function setTemplateAfter( mixed $templateAfter );

Appends template after controller layout

setTemplateBefore()

public function setTemplateBefore( mixed $templateBefore );

Appends template before controller layout

start()

public function start();

Starts rendering process enabling the output buffering

Mvc\View\Engine\AbstractEngine

Abstract Source on GitHub

All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\Mvc\View component.

Uses Phalcon\Di\DiInterface · Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Mvc\ViewBaseInterface

Method Summary

Properties

protected ManagerInterface|null $eventsManager = null
protected ViewBaseInterface $view

Methods

Public · 6

__construct()

public function __construct(
    ViewBaseInterface $view,
    DiInterface $container = null
);

Phalcon\Mvc\View\Engine constructor

getContent()

public function getContent(): string;

Returns cached output on another view stage

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

getView()

public function getView(): ViewBaseInterface;

Returns the view component related to the adapter

partial()

public function partial(
    string $partialPath,
    mixed $params = null
): void;

Renders a partial inside another view

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\View\Engine\EngineInterface

Interface Source on GitHub

Interface for Phalcon\Mvc\View engine adapters

  • Phalcon\Mvc\View\Engine\EngineInterface

Method Summary

Methods

Public · 3

getContent()

public function getContent(): string;

Returns cached output on another view stage

partial()

public function partial(
    string $partialPath,
    mixed $params = null
): void;

Renders a partial inside another view

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 Source on GitHub

Adapter to use PHP itself as templating engine

Method Summary

Methods

Public · 1

render()

public function render(
    string $path,
    mixed $params,
    bool $mustClean = false
);

Renders a view using the template engine

Mvc\View\Engine\Volt

Class Source on GitHub

Designer friendly and fast template engine for PHP written in Zephir/C

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 · Phalcon\Traits\Php\InfoTrait

Method Summary

Properties

protected Compiler $compiler
protected ManagerInterface|null $eventsManager
protected array $macros = []
protected array $options = []

Methods

Public · 13

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()

public function convertEncoding(
    string $text,
    string $from,
    string $to
): string;

Performs a string conversion

getCompiler()

public function getCompiler(): Compiler;

Returns the Volt's compiler

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

getOptions()

public function getOptions(): array;

Return Volt's options

isIncluded()

public function isIncluded(
    mixed $needle,
    mixed $haystack
): bool;

Checks if the needle is included in the haystack

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()

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()

public function render(
    string $path,
    mixed $params,
    bool $mustClean = false
);

Renders a view using the template engine

setEventsManager()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

setOptions()

public function setOptions( array $options );

Set Volt's options

slice()

public function slice(
    mixed $value,
    int $start = 0,
    mixed $end = null
);

Extracts a slice from a string/array/traversable object value

sort()

public function sort( array $value ): array;

Sorts an array

Mvc\View\Engine\Volt\Compiler

Class Source on GitHub

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();

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 · Phalcon\Traits\Php\FileTrait

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()

public function __construct( ViewBaseInterface $view = null );

Phalcon\Mvc\View\Engine\Volt\Compiler

addExtension()

public function addExtension( mixed $extension ): static;

Registers a Volt's extension

addFilter()

public function addFilter(
    string $name,
    mixed $definition
): static;

Register a new filter in the compiler

addFunction()

public function addFunction(
    string $name,
    mixed $definition
): static;

Register a new function in the compiler

attributeReader()

public function attributeReader( array $expr ): string;

Resolves attribute reading

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()

public function compileAutoEscape(
    array $statement,
    bool $extendsMode
): string;

Compiles a "autoescape" statement returning PHP code

compileCall()

public function compileCall(
    array $statement,
    bool $extendsMode
): string;

Compiles calls to macros

compileCase()

public function compileCase(
    array $statement,
    bool $caseClause = true
): string;

Compiles a "case"/"default" clause returning PHP code

compileDo()

public function compileDo( array $statement ): string;

Compiles a "do" statement returning PHP code

compileEcho()

public function compileEcho( array $statement ): string;

Compiles a {{ }} statement returning PHP code

compileElseIf()

public function compileElseIf( array $statement ): string;

Compiles a "elseif" statement returning PHP code

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()

public function compileForElse(): string;

Generates a 'forelse' PHP code

compileForeach()

public function compileForeach(
    array $statement,
    bool $extendsMode = false
): string;

Compiles a "foreach" intermediate code representation into plain PHP code

compileIf()

public function compileIf(
    array $statement,
    bool $extendsMode = false
): string;

Compiles a 'if' statement returning PHP code

compileInclude()

public function compileInclude( array $statement ): string;

Compiles a 'include' statement returning PHP code

compileMacro()

public function compileMacro(
    array $statement,
    bool $extendsMode
): string;

Compiles macros

compileReturn()

public function compileReturn( array $statement ): string;

Compiles a "return" statement returning PHP code

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()

public function compileString(
    string $viewCode,
    bool $extendsMode = false
): string;

Compiles a template into a string

echo $compiler->compileString('{{ "hello world" }}');

compileSwitch()

public function compileSwitch(
    array $statement,
    bool $extendsMode = false
): string;

Compiles a 'switch' statement returning PHP code

expression()

final public function expression(
    array $expr,
    bool $doubleQuotes = false
): string;

Resolves an expression node in an AST volt tree

fireExtensionEvent()

final public function fireExtensionEvent(
    string $name,
    array $arguments = []
);

Fires an event to registered extensions

functionCall()

public function functionCall(
    array $expr,
    bool $doubleQuotes = false
): string;

Resolves function intermediate code into PHP function calls

getCompiledTemplatePath()

public function getCompiledTemplatePath(): string;

Returns the path to the last compiled template

getDI()

public function getDI(): DiInterface;

Returns the internal dependency injector

getExtensions()

public function getExtensions(): array;

Returns the list of extensions registered in Volt

getFilters()

public function getFilters(): array;

Register the user registered filters

getFunctions()

public function getFunctions(): array;

Register the user registered functions

getOption()

public function getOption( string $option ): string|null;

Returns a compiler's option

getOptions()

public function getOptions(): array;

Returns the compiler options

getTemplatePath()

public function getTemplatePath(): string;

Returns the path that is currently being compiled

getUniquePrefix()

public function getUniquePrefix(): string;

Return a unique prefix to be used as prefix for compiled variables and contexts

parse()

public function parse( string $viewCode ): array;

Parses a Volt template returning its intermediate representation

print_r(
    $compiler->parse("{{ 3 + 2 }}")
);

resolveTest()

public function resolveTest(
    array $test,
    string $left
): string;

Resolves filter intermediate code into a valid PHP expression

setDI()

public function setDI( DiInterface $container ): void;

Sets the dependency injector

setOption()

public function setOption(
    string $option,
    mixed $value
): static;

Sets a single compiler option

setOptions()

public function setOptions( array $options ): static;

Sets the compiler options

setUniquePrefix()

public function setUniquePrefix( string $prefix ): static;

Set a unique prefix to be used as prefix for compiled variables

Protected · 5

compileSource()

protected function compileSource(
    string $viewCode,
    bool $extendsMode = false
): array|string;

Compiles a Volt source code returning a PHP plain version

getFinalPath()

protected function getFinalPath( string $path );

Gets the final path with VIEW

resolveFilter()

final protected function resolveFilter(
    array $filter,
    string $left
): string;

Resolves filter intermediate code into PHP function calls

statementList()

final protected function statementList(
    array $statements,
    bool $extendsMode = false
): string;

Traverses a statement list compiling each of its nodes

statementListOrExtends()

final protected function statementListOrExtends( mixed $statements );

Compiles a block of statements

Mvc\View\Engine\Volt\Exception

Class Source on GitHub

Class for exceptions thrown by Phalcon\Mvc\View

Uses Phalcon\Mvc\View\Exception

Method Summary

Properties

protected array $statement = []

Methods

Public · 2

__construct()

public function __construct(
    string $message = "",
    array $statement = [],
    int $code = 0,
    \Exception $previous = null
);

getStatement()

public function getStatement(): array;

Gets currently parsed statement (if any).

Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $path );

Mvc\View\Engine\Volt\Exceptions\CorruptedStatement

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( array $statement );

Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidExtension

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidHaystack

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidOptionType

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $option,
    string $type
);

Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidPathType

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidStatement

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $file,
    int $line,
    array $statement
);

Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $file,
    int $line
);

Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $file,
    int $line
);

Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\View\Engine\Volt\Exceptions\MacroNotFound

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\View\Engine\Volt\Exceptions\MbstringRequired

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $path );

Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $path );

Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    int $type,
    string $file,
    int $line
);

Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $name,
    string $file,
    int $line
);

Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $file,
    int $line
);

Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    int $type,
    string $file,
    int $line
);

Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable

Class Source on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exception

Class Source on GitHub

Phalcon\Mvc\View\Exception

Class for exceptions thrown by Phalcon\Mvc\View

Mvc\View\Exceptions\InvalidEngineRegistration

Class Source on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $extension );

Mvc\View\Exceptions\InvalidViewsDirType

Class Source on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exceptions\SimpleViewNotFound

Class Source on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $viewsDirPath );

Mvc\View\Exceptions\SimpleViewServicesUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exceptions\ViewNotFound

Class Source on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $viewPath );

Mvc\View\Exceptions\ViewServicesUnavailable

Class Source on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exceptions\ViewsDirItemMustBeString

Class Source on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Simple

Class Source on GitHub

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,
    ]
);

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 · Phalcon\Mvc\View\Traits\ViewParamsTrait · Phalcon\Traits\Php\FileTrait · Phalcon\Traits\Support\Helper\Str\DirSeparatorTrait

Method Summary

Properties

protected string $activeRenderPath
protected EngineInterface[]|false $engines = false
protected ManagerInterface|null $eventsManager
protected array $options = []
protected string $viewsDir

Methods

Public · 13

__construct()

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

Phalcon\Mvc\View\Simple constructor

__get()

public function __get( string $key ): mixed|null;

Magic method to retrieve a variable passed to the view

echo $this->view->products;

__set()

public function __set(
    string $key,
    mixed $value
): void;

Magic method to pass variables to the views

$this->view->products = $products;

getActiveRenderPath()

public function getActiveRenderPath(): string;

Returns the path of the view that is currently rendered

getEventsManager()

public function getEventsManager(): ManagerInterface|null;

Returns the internal event manager

getViewsDir()

public function getViewsDir(): string;

Gets views directory

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()

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()

public function render(
    string $path,
    array $params = []
): string;

Renders a view

setEventsManager()

public function setEventsManager( ManagerInterface $eventsManager ): void;

Sets the events manager

setParamToView()

public function setParamToView(
    string $key,
    mixed $value
): static;

Adds parameters to views (alias of setVar)

$this->view->setParamToView("products", $products);

setVars()

public function setVars(
    array $params,
    bool $merge = true
): static;

Set all the render params

$this->view->setVars(
    [
        "products" => $products,
    ]
);

setViewsDir()

public function setViewsDir( string $viewsDir ): void;

Sets views directory

Protected · 2

internalRender()

final protected function internalRender(
    string $path,
    mixed $params
): void;

Tries to render the view with every engine registered in the component

loadTemplateEngines()

protected function loadTemplateEngines(): array;

Loads registered template engines, if none are registered it will use Phalcon\Mvc\View\Engine\Php