Skip to content

Phalcon Mvc

Updated View as Markdown

Mvc\Application

ClassSource 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

protectedbool$implicitView = true
protectedbool$sendCookies = true
protectedbool$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

ClassSource on GitHub

Phalcon\Mvc\Application\Exception

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

Mvc\Application\Exceptions\ContainerRequired

ClassSource on GitHub

Uses Phalcon\Mvc\Application\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Application\Exceptions\InvalidModuleDefinition

ClassSource on GitHub

Uses Phalcon\Mvc\Application\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Application\Exceptions\ModuleDefinitionPathNotFound

ClassSource on GitHub

Uses Phalcon\Mvc\Application\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $path );

Mvc\Controller

AbstractSource 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

InterfaceSource on GitHub

Phalcon\Mvc\ControllerInterface

Interface for controller handlers

  • Phalcon\Mvc\ControllerInterface

Mvc\Controller\BindModelInterface

InterfaceSource 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

ClassSource 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\Contracts\Dispatcher\DispatcherTypes · Phalcon\Dispatcher\AbstractDispatcher · Phalcon\Events\ManagerInterface · Phalcon\Http\ResponseInterface · Phalcon\Mvc\Dispatcher\Exception · Phalcon\Mvc\Dispatcher\Exceptions\ResponseServiceUnavailable

Method Summary

Properties

protectedstring$defaultAction = "index"
protectedstring$defaultHandler = "index"
protectedstring$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

InterfaceSource on GitHub

Phalcon\Mvc\DispatcherInterface

Interface for Phalcon\Mvc\Dispatcher

Uses Phalcon\Contracts\Mvc\Dispatcher

Mvc\Dispatcher\Exception

ClassSource on GitHub

Phalcon\Mvc\Dispatcher\Exception

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

Mvc\Dispatcher\Exceptions\ResponseServiceUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\Dispatcher\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\EntityInterface

InterfaceSource 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

ClassSource 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|null$container = null )Phalcon\Mvc\Micro constructorpublicstaticafter( mixed$handler )Appends an 'after' middleware to be called after execute the routepublicstaticafterBinding( mixed$handler )Appends a afterBinding middleware to be called after model bindingpublicstaticbefore( mixed$handler )Appends a before middleware to be called before execute the routepublicRouteInterfacedelete(string$routePattern,mixed$handler)Maps a route to a handler that only matches if the HTTP method is DELETEpublicstaticerror( mixed$handler )Sets a handler that will be called when an exception is thrown handlingpublicstaticfinish( mixed$handler )Appends a 'finish' middleware to be called when the request is finishedpublicRouteInterfaceget(string$routePattern,mixed$handler)Maps a route to a handler that only matches if the HTTP method is GETpublicgetActiveHandler()Return the handler that will be called for the matched routepublicarraygetBoundModels()Returns bound models from binder instancepublicManagerInterface|nullgetEventsManager()Returns the internal event managerpublicarraygetHandlers()Returns the internal handlers attached to the applicationpublicBinderInterface|nullgetModelBinder()Gets model binderpublicgetReturnedValue()Returns the value returned by the executed handlerpublicRouterInterfacegetRouter()Returns the internal router used by the applicationpublicgetService( string$serviceName )Obtains a service from the DIpublicgetSharedService( string$serviceName )Obtains a shared service from the DIpublichandle( string$uri )Handle the whole requestpublicboolhasService( string$serviceName )Checks if a service is registered in the DIpublicRouteInterfacehead(string$routePattern,mixed$handler)Maps a route to a handler that only matches if the HTTP method is HEADpublicRouteInterfacemap(string$routePattern,mixed$handler)Maps a route to a handler without any HTTP method constraintpublicstaticmount( CollectionInterface$collection )Mounts a collection of handlerspublicstaticnotFound( mixed$handler )Sets a handler that will be called when the router does not match any ofpublicbooloffsetExists( mixed$offset )Check if a service is registered in the internal services container usingpublicmixedoffsetGet( mixed$offset )Allows to obtain a shared service in the internal services containerpublicvoidoffsetSet(mixed$offset,mixed$value)Allows to register a shared service in the internal services containerpublicvoidoffsetUnset( mixed$offset )Removes a service from the internal services container using the arraypublicRouteInterfaceoptions(string$routePattern,mixed$handler)Maps a route to a handler that only matches if the HTTP method is OPTIONSpublicRouteInterfacepatch(string$routePattern,mixed$handler)Maps a route to a handler that only matches if the HTTP method is PATCHpublicRouteInterfacepost(string$routePattern,mixed$handler)Maps a route to a handler that only matches if the HTTP method is POSTpublicRouteInterfaceput(string$routePattern,mixed$handler)Maps a route to a handler that only matches if the HTTP method is PUTpublicselfsetActiveHandler( mixed$activeHandler )Sets externally the handler that must be called by the matched routepublicvoidsetDI( DiInterface$container )Sets the DependencyInjector containerpublicvoidsetEventsManager( ManagerInterface$eventsManager )Sets the events managerpublicstaticsetModelBinder(BinderInterface$modelBinder,mixed$cache = null)Sets model binderpublicstaticsetResponseHandler( mixed$handler )Appends a custom 'response' handler to be called instead of the defaultpublicServiceInterfacesetService(string$serviceName,mixed$definition,bool$isShared = false)Sets a service from the DIpublicvoidstop()Stops the middleware execution avoiding than other middlewares be

Properties

protectedcallable|null$activeHandler = null
protectedarray$afterBindingHandlers = []
protectedarray$afterHandlers = []
protectedarray$beforeHandlers = []
protectedDiInterface|null$container = null
protectedcallable|null$errorHandler = null
protectedManagerInterface|null$eventsManager = null
protectedarray$finishHandlers = []
protectedarray$handlers = []
protectedBinderInterface|null$modelBinder = null
protectedcallable|null$notFoundHandler = null
protectedcallable|null$responseHandler = null
protectedmixed|null$returnedValue = null
protectedRouterInterface|null$router = null
protectedbool$stopped = false

Methods

Public · 38

__construct()

public function __construct( DiInterface|null $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

ClassSource 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

publicCollectionInterfacedelete(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is DELETE.publicCollectionInterfaceget(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is GET.publicmixedgetHandler()Returns the main handlerpublicarraygetHandlers()Returns the registered handlerspublicstringgetPrefix()Returns the collection prefix if anypublicCollectionInterfacehead(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is HEAD.publicboolisLazy()Returns if the main handler must be lazy loadedpublicCollectionInterfacemap(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler.publicCollectionInterfacemapVia(string$routePattern,callable$handler,mixed$method,string|null$name = null)Maps a route to a handler via methods.publicCollectionInterfaceoptions(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method ispublicCollectionInterfacepatch(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is PATCH.publicCollectionInterfacepost(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is POST.publicCollectionInterfaceput(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is PUT.publicCollectionInterfacesetHandler(mixed$handler,bool$isLazy = false)Sets the main handler.publicCollectionInterfacesetLazy( bool$isLazy )Sets if the main handler must be lazy loadedpublicCollectionInterfacesetPrefix( string$prefix )Sets a prefix for all routes added to the collectionprotectedvoidaddMap(mixed$method,string$routePattern,callable$handler,string|null$name = null)Internal function to add a handler to the group.

Properties

protectedcallable$handler
protectedarray$handlers = []
protectedbool$isLazy = false
protectedstring$prefix = ""

Methods

Public · 16

delete()

public function delete(
    string $routePattern,
    callable $handler,
    string|null $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|null $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|null $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|null $name = null
): CollectionInterface;

Maps a route to a handler.

mapVia()

public function mapVia(
    string $routePattern,
    callable $handler,
    mixed $method,
    string|null $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|null $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|null $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|null $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|null $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|null $name = null
): void;

Internal function to add a handler to the group.

Mvc\Micro\CollectionInterface

InterfaceSource on GitHub

Phalcon\Mvc\Micro\CollectionInterface

Interface for Phalcon\Mvc\Micro\Collection

  • Phalcon\Mvc\Micro\CollectionInterface

Method Summary

publicCollectionInterfacedelete(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is DELETEpublicCollectionInterfaceget(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is GETpublicmixedgetHandler()Returns the main handlerpublicarraygetHandlers()Returns the registered handlerspublicstringgetPrefix()Returns the collection prefix if anypublicCollectionInterfacehead(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is HEADpublicboolisLazy()Returns if the main handler must be lazy loadedpublicCollectionInterfacemap(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handlerpublicCollectionInterfaceoptions(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is OPTIONSpublicCollectionInterfacepatch(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is PATCHpublicCollectionInterfacepost(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is POSTpublicCollectionInterfaceput(string$routePattern,callable$handler,string|null$name = null)Maps a route to a handler that only matches if the HTTP method is PUTpublicCollectionInterfacesetHandler(mixed$handler,bool$isLazy = false)Sets the main handlerpublicCollectionInterfacesetLazy( bool$isLazy )Sets if the main handler must be lazy loadedpublicCollectionInterfacesetPrefix( string$prefix )Sets a prefix for all routes added to the collection

Methods

Public · 15

delete()

public function delete(
    string $routePattern,
    callable $handler,
    string|null $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|null $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|null $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|null $name = null
): CollectionInterface;

Maps a route to a handler

options()

public function options(
    string $routePattern,
    callable $handler,
    string|null $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|null $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|null $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|null $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

ClassSource on GitHub

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

Mvc\Micro\Exceptions\ContainerRequired

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\ErrorHandlerNotCallable

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\HandlerNotCallable

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Micro\Exceptions\InvalidRegisteredHandler

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\LazyHandlerNotFound

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $definition );

Mvc\Micro\Exceptions\MissingCollectionMainHandler

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\NoHandlersToMount

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\NoMatchedRouteHandler

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\NotFoundHandlerNotCallable

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\Exceptions\ResponseHandlerNotCallable

ClassSource on GitHub

Uses Phalcon\Mvc\Micro\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Micro\LazyLoader

ClassSource 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

protectedstring$definition
protectedobject|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|null $modelBinder = null
);

Calling __call method

getDefinition()

public function getDefinition(): string;

getHandler()

public function getHandler(): object|null;

Mvc\Micro\MiddlewareInterface

InterfaceSource 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

AbstractSource 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\Eager\Loader · Phalcon\Mvc\Model\Eager\PathTree · 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\InvalidEagerParameter · 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\UnsupportedEagerHydration · Phalcon\Mvc\Model\Exceptions\UnsupportedEagerResultset · 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\Resultset\Simple · 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 implementedpublic__callStatic(string$method,array$arguments)Handles method calls when a static method is not implementedpublic__construct(mixed$data = null,DiInterface|null$container = null,ManagerInterface|null$modelsManager = null)Phalcon\Mvc\Model constructorpublic__get( string$property )Magic method to get related records using the relation alias as apublicbool__isset( string$property )Magic method to check if a property is a valid relationpublicarray__serialize()Serializes a modelpublic__set(string$property,mixed$value)Magic method to assign values to the the modelpublicvoid__unserialize( array$data )Unserializes an array to the modelpublicvoidaddBehavior( BehaviorInterface$behavior )Setups a behavior in a modelpublicModelInterfaceappendMessage( MessageInterface$message )Appends a customized message on the validation processpublicvoidappendMessagesFrom( mixed$model )Append messages to this model from another Model.publicModelInterfaceassign(array$data,mixed$whiteList = null,mixed$dataColumnMap = null)Assigns values to a model from an arraypublicfloat|ResultsetInterfaceaverage( array$parameters = [] )Returns the average value on a column for a result-set of rows matchingpublicModelInterfacecloneResult(ModelInterface$base,array$data,int$dirtyState = 0)Assigns values to a model from an array returning a new modelpublicModelInterfacecloneResultMap(mixed$base,array$data,mixed$columnMap,int$dirtyState = 0,bool|null$keepSnapshots = null)Assigns values to a model from an array, returning a new model.publiccloneResultMapHydrate(array$data,mixed$columnMap,int$hydrationMode)Returns an hydrated result based on the data and the column mappublicint|ResultsetInterfacecount( mixed$parameters = null )Counts how many records match the specified conditions.publicboolcreate()Inserts a model instance. If the instance already exists in thepublicbooldelete()Deletes a model instance. Returning true on success or false otherwise.publicbooldoSave( CollectionInterface$visited )Inserted or updates model instance, expects a visited list of objects.publicarraydump()Returns a simple representation of the object that can be used withpublicResultsetInterfacefind( mixed$parameters = null )Query for a set of records that match the specified conditionspublicmixed|nullfindFirst( mixed$parameters = null )Query the first record that matches the specified conditionspublicboolfireEvent( string$eventName )Fires an event, implicitly calls behaviors and listeners in the eventspublicboolfireEventCancel( string$eventName )Fires an event, implicitly calls behaviors and listeners in the eventspublicarraygetChangedFields()Returns a list of changed values.publicintgetDirtyState()Returns one of the DIRTY_STATE_* constants telling if the record existspublicEventsManagerInterface|nullgetEventsManager()Returns the custom events manager or null if there is no custom events managerpublicMessageInterface[]getMessages( mixed$filter = null )Returns array of validation messagespublicManagerInterfacegetModelsManager()Returns the models manager related to the entity instancepublicMetaDataInterfacegetModelsMetaData(){@inheritdoc}publicarraygetOldSnapshotData()Returns the internal old snapshot datapublicintgetOperationMade()Returns the type of the latest operation performed by the ORMpublicAdapterInterfacegetReadConnection()Gets the connection used to read data for the modelpublicstringgetReadConnectionService()Returns the DependencyInjection connection service name used to read datapublicgetRelated(string$alias,mixed$arguments = null)Returns related records based on defined relationspublicstring|nullgetSchema()Returns schema name where the mapped table is locatedpublicarraygetSnapshotData()Returns the internal snapshot datapublicstringgetSource()Returns the table name mapped in the modelpublicTransactionInterface|nullgetTransaction()publicarraygetUpdatedFields()Returns a list of updated values.publicAdapterInterfacegetWriteConnection()Gets the connection used to write data to the modelpublicstringgetWriteConnectionService()Returns the DependencyInjection connection service name used to writepublicboolhasChanged(mixed$fieldName = null,bool$allFields = false)Check if a specific attribute has changedpublicboolhasSnapshotData()Checks if the object has internal snapshot datapublicboolhasUpdated(mixed$fieldName = null,bool$allFields = false)Check if a specific attribute was updatedpublicboolisRelationshipLoaded( string$relationshipAlias )Checks if saved related records have already been loaded.publicarrayjsonSerialize()Serializes the object for json_encodepublicmixedmaximum( mixed$parameters = null )Returns the maximum value of a column for a result-set of rows that matchpublicmixedminimum( mixed$parameters = null )Returns the minimum value of a column for a result-set of rows that matchpublicCriteriaInterfacequery( DiInterface|null$container = null )Create a criteria for a specific modelpublicmixed|nullreadAttribute( string$attribute )Reads an attribute value by its namepublicModelInterfacerefresh()Refreshes the model attributes re-querying the record from the databasepublicboolsave()Inserts or updates a model instance. Returning true on success or falsepublicstring|nullserialize()Serializes the object ignoring connections, services, related objects orpublicvoidsetConnectionService( string$connectionService )Sets the DependencyInjection connection service namepublicModelInterface|boolsetDirtyState( int$dirtyState )Sets the dirty state of the object using one of the DIRTY_STATE_* constantspublicsetEventsManager( EventsManagerInterface$eventsManager )Sets a custom events managerpublicsetOldSnapshotData(array$data,mixed$columnMap = null)Sets the record's old snapshot data.publicvoidsetReadConnectionService( string$connectionService )Sets the DependencyInjection connection service name used to read datapublicModelInterfacesetRelated(string$alias,mixed$records)Stores related records in the relation cache, so that a subsequentpublicvoidsetSnapshotData(array$data,mixed$columnMap = null)Sets the record's snapshot data.publicModelInterfacesetSync(mixed$elements = null,bool$enabled = true)Marks one or more many-to-many relationships to be synchronized (or not)publicModelInterfacesetTransaction( TransactionInterface$transaction )Sets a transaction related to the Model instancepublicvoidsetWriteConnectionService( string$connectionService )Sets the DependencyInjection connection service name used to write datapublicvoidsetup( array$options )Enables/disables options in the ORM.publicvoidskipOperation( bool$skip )Skips the current operation forcing a success statepublicfloat|ResultsetInterfacesum( mixed$parameters = null )Calculates the sum on a column for a result-set of rows that match thepublicarraytoArray(mixed$columns = null,mixed$useGetter = true)Returns the instance as an array representationpublicvoidunserialize( string$data )Unserializes the object from a serialized stringpublicboolupdate()Updates a model instance. If the instance does not exist in thepublicboolvalidationHasFailed()Check whether validation process has generated any messagespublicvoidwriteAttribute(string$attribute,mixed$value)Writes an attribute value by its nameprotectedvoidallowEmptyStringValues( array$attributes )Sets a list of attributes that must be skipped from theprotectedRelationbelongsTo(mixed$fields,string$referenceModel,mixed$referencedFields,array$options = [])Setup a reverse 1-1 or n-1 relation between two modelsprotectedcancelOperation()Cancel the current operationprotectedboolcheckForeignKeysRestrict()Reads "belongs to" relations and check the virtual foreign keys whenprotectedboolcheckForeignKeysReverseCascade()Reads both "hasMany" and "hasOne" relations and checks the virtualprotectedboolcheckForeignKeysReverseRestrict()Reads both "hasMany" and "hasOne" relations and checks the virtualprotectedarraycollectRelatedToSave()Collects previously queried (belongs-to, has-one and has-one-through)protectedbooldoLowInsert(MetaDataInterface$metaData,AdapterInterface$connection,mixed$table,mixed$identityField)Sends a pre-build INSERT SQL statement to the relational database systemprotectedbooldoLowUpdate(MetaDataInterface$metaData,AdapterInterface$connection,mixed$table)Sends a pre-build UPDATE SQL statement to the relational database systemprotectedgetRelatedRecords(string$modelName,string$method,array$arguments)Returns related records defined relations depending on the method name.protectedmixedgroupResult(string$functionName,string$alias,mixed$parameters = null)Generate a PHQL SELECT statement for an aggregateprotectedboolhas(MetaDataInterface$metaData,AdapterInterface$connection)Checks whether the current record already existsprotectedRelationhasMany(mixed$fields,string$referenceModel,mixed$referencedFields,array$options = [])Setup a 1-n relation between two modelsprotectedRelationhasManyToMany(mixed$fields,string$intermediateModel,mixed$intermediateFields,mixed$intermediateReferencedFields,string$referenceModel,mixed$referencedFields,array$options = [])Setup an n-n relation between two models, through an intermediateprotectedRelationhasOne(mixed$fields,string$referenceModel,mixed$referencedFields,array$options = [])Setup a 1-1 relation between two modelsprotectedRelationhasOneThrough(mixed$fields,string$intermediateModel,mixed$intermediateFields,mixed$intermediateReferencedFields,string$referenceModel,mixed$referencedFields,array$options = [])Setup a 1-1 relation between two models, through an intermediateprotectedinvokeFinder(string$method,array$arguments)Try to check if the query must invoke a finderprotectedvoidkeepSnapshots( bool$keepSnapshot )Sets if the model must keep the original record snapshot in memoryprotectedboolpossibleSetter(string$property,mixed$value)Check for, and attempt to use, possible setter.protectedboolpostSave(bool$success,bool$exists)Executes internal events after save a recordprotectedboolpostSaveRelatedRecords(AdapterInterface$connection,mixed$related,CollectionInterface$visited)Save the related records assigned in the has-one/has-many relationsprotectedboolpreSave(MetaDataInterface$metaData,bool$exists,mixed$identityField)Executes internal hooks before save a recordprotectedboolpreSaveRelatedRecords(AdapterInterface$connection,mixed$related,CollectionInterface$visited)Saves related records that must be stored prior to save the master recordprotectedModelInterfacesetSchema( string$schema )Sets schema name where the mapped table is locatedprotectedModelInterfacesetSource( string$source )Sets the table name to which model should be mappedprotectedvoidskipAttributes( array$attributes )Sets a list of attributes that must be skipped from theprotectedvoidskipAttributesOnCreate( array$attributes )Sets a list of attributes that must be skipped from theprotectedvoidskipAttributesOnUpdate( array$attributes )Sets a list of attributes that must be skipped from theprotectedvoiduseDynamicUpdate( bool$dynamicUpdate )Sets if a model must use dynamic update instead of the all-field updateprotectedboolvalidate( ValidationInterface$validator )Executes validators on every validation call

Constants

intDIRTY_STATE_DETACHED = 2
intDIRTY_STATE_PERSISTENT = 0
intDIRTY_STATE_TRANSIENT = 1
intOP_CREATE = 1
intOP_DELETE = 3
intOP_NONE = 0
intOP_UPDATE = 2
stringTRANSACTION_INDEX = "transaction"

Properties

protectedarray$dirtyRelated = []
protectedint$dirtyState = 1
protectedarray$errorMessages = []
protectedManagerInterface|null$modelsManager = null
protectedMetaDataInterface|null$modelsMetaData = null
protectedarray$oldSnapshot = []
protectedint$operationMade = 0
protectedarray$rawValues = []
protectedarray$related = []
protectedbool$skipped = false
protectedarray$snapshot = []
protectedarray$syncRelated = []Per-save many-to-many sync overrides, keyed by lowercased relation alias (or "*" wildcard) => bool. Cleared after each save().
protectedTransactionInterface|null$transaction = null
protectedstring|null$uniqueKey = null
protectedarray$uniqueParams = []
protectedarray$uniqueTypes = []

Methods

Public · 73

__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|null $container = null,
    ManagerInterface|null $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 = [] ): float|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|null $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;

// behavior 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|null $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

setRelated()

public function setRelated(
    string $alias,
    mixed $records
): ModelInterface;

Stores related records in the relation cache, so that a subsequent getRelated() or property access returns them without querying.

This is the write side of the cache getRelated() already reads. It does not mark the record dirty: the value lands in related, never in dirtyRelated, so save() is unaffected.

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

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

InterfaceSource 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

publicModelInterfaceappendMessage( MessageInterface$message )Appends a customized message on the validation processpublicModelInterfaceassign(array$data,mixed$whiteList = null,mixed$dataColumnMap = null)Assigns values to a model from an arraypublicfloat|ResultsetInterfaceaverage( array$parameters = [] )Allows to calculate the average value on a column matching the specifiedpublicModelInterfacecloneResult(ModelInterface$base,array$data,int$dirtyState = 0)Assigns values to a model from an array returning a new modelpublicModelInterfacecloneResultMap(mixed$base,array$data,mixed$columnMap,int$dirtyState = 0,bool$keepSnapshots = false)Assigns values to a model from an array returning a new modelpubliccloneResultMapHydrate(array$data,mixed$columnMap,int$hydrationMode)Returns an hydrated result based on the data and the column mappublicint|ResultsetInterfacecount( mixed$parameters = null )Allows to count how many records match the specified conditionspublicboolcreate()Inserts a model instance. If the instance already exists in thepublicbooldelete()Deletes a model instance. Returning true on success or false otherwise.publicfind( mixed$parameters = null )Allows to query a set of records that match the specified conditions.publicmixed|nullfindFirst( mixed$parameters = null )Allows to query the first record that match the specified conditionspublicboolfireEvent( string$eventName )Fires an event, implicitly calls behaviors and listeners in the eventspublicboolfireEventCancel( string$eventName )Fires an event, implicitly calls behaviors and listeners in the eventspublicintgetDirtyState()Returns one of the DIRTY_STATE_* constants telling if the record existspublicMessageInterface[]getMessages()Returns array of validation messagespublicMetaDataInterfacegetModelsMetaData()Returns the models meta-data service related to the entity instance.publicintgetOperationMade()Returns the type of the latest operation performed by the ORMpublicAdapterInterfacegetReadConnection()Gets internal database connectionpublicstringgetReadConnectionService()Returns DependencyInjection connection service used to read datapublicgetRelated(string$alias,mixed$arguments = null)Returns related records based on defined relationspublicstring|nullgetSchema()Returns schema name where table mapped is locatedpublicstringgetSource()Returns table name mapped in the modelpublicAdapterInterfacegetWriteConnection()Gets internal database connectionpublicstringgetWriteConnectionService()Returns DependencyInjection connection service used to write datapublicmixedmaximum( mixed$parameters = null )Allows to get the maximum value of a column that match the specifiedpublicmixedminimum( mixed$parameters = null )Allows to get the minimum value of a column that match the specifiedpublicCriteriaInterfacequery( DiInterface|null$container = null )Create a criteria for a specific modelpublicModelInterfacerefresh()Refreshes the model attributes re-querying the record from the databasepublicboolsave()Inserts or updates a model instance. Returning true on success or falsepublicvoidsetConnectionService( string$connectionService )Sets both read/write connection servicespublicModelInterface|boolsetDirtyState( int$dirtyState )Sets the dirty state of the object using one of the DIRTY_STATE_*publicvoidsetReadConnectionService( string$connectionService )Sets the DependencyInjection connection service used to read datapublicvoidsetSnapshotData(array$data,mixed$columnMap = null)Sets the record's snapshot data. This method is used internally to setpublicModelInterfacesetSync(mixed$elements = null,bool$enabled = true)Marks one or more many-to-many relationships to be synchronized (or not)publicModelInterfacesetTransaction( TransactionInterface$transaction )Sets a transaction related to the Model instancepublicvoidsetWriteConnectionService( string$connectionService )Sets the DependencyInjection connection service used to write datapublicvoidskipOperation( bool$skip )Skips the current operation forcing a success statepublicfloat|ResultsetInterfacesum( mixed$parameters = null )Allows to calculate a sum on a column that match the specified conditionspublicboolupdate()Updates a model instance. If the instance does not exist in thepublicboolvalidationHasFailed()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 = [] ): float|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|null $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 ): float|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

AbstractSource on GitHub

Phalcon\Mvc\Model\Behavior

This is an optional base class for ORM behaviors

Uses Phalcon\Mvc\ModelInterface

Method Summary

Properties

protectedarray$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|null $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

InterfaceSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $option );

Mvc\Model\Behavior\SoftDelete

ClassSource 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

ClassSource 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

ClassSource 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 · 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

protectedarray$boundModels = []Array for storing active bound models
protectedAdapterInterface|null$cacheCache object used for caching parameters for model binding
protectedarray$internalCache = []Internal cache for caching parameters for model binding during request
protectedarray$originalValues = []Array for original values

Methods

Public · 6

__construct()

public function __construct( AdapterInterface|null $cache = null );

Phalcon\Mvc\Model\Binder constructor

bindToHandler()

public function bindToHandler(
    object $handler,
    array $params,
    string $cacheKey,
    string|null $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

InterfaceSource 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|null $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

InterfaceSource 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

ClassSource 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

publicCriteriaInterfaceandWhere(string$conditions,mixed$bindParams = null,mixed$bindTypes = null)Appends a condition to the current conditions using an AND operatorpublicCriteriaInterfacebetweenWhere(string$expr,mixed$minimum,mixed$maximum)Appends a BETWEEN condition to the current conditionspublicCriteriaInterfacebind(array$bindParams,bool$merge = false)Sets the bound parameters in the criteriapublicCriteriaInterfacebindTypes( array$bindTypes )Sets the bind types in the criteriapublicCriteriaInterfacecache( array$cache )Sets the cache options in the criteriapublicCriteriaInterfacecolumns( mixed$columns )Sets the columns to be queried. The columns can be either a string orpublicCriteriaInterfaceconditions( string$conditions )Adds the conditions parameter to the criteriapublicBuilderInterfacecreateBuilder()Creates a query builder from criteria.publicCriteriaInterfacedistinct( mixed$distinct )Sets SELECT DISTINCT / SELECT ALL flagpublicCriteriaeager( array$paths )Pre-loads the named relations when the criteria is executedpublicResultsetInterfaceexecute()Executes a find using the parameters built with the criteriapublicCriteriaInterfaceforUpdate( bool$forUpdate = true )Adds the "for_update" parameter to the criteriapublicCriteriaInterfacefromInput(DiInterface$container,string$modelName,array$data,string$operator = "AND")Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POSTpublicstring|array|nullgetColumns()Returns the columns to be queriedpublicstring|nullgetConditions()Returns the conditions parameter in the criteriapublicDiInterfacegetDI()Returns the DependencyInjector containerpublicgetGroupBy()Returns the group clause in the criteriapublicgetHaving()Returns the having clause in the criteriapublicint|array|nullgetLimit()Returns the limit parameter in the criteria, which will bepublicstringgetModelName()Returns an internal model name on which the criteria will be appliedpublicstring|nullgetOrderBy()Returns the order clause in the criteriapublicarraygetParams()Returns all the parameters defined in the criteriapublicstring|nullgetWhere()Returns the conditions parameter in the criteriapublicCriteriaInterfacegroupBy( mixed$group )Adds the group-by clause to the criteriapublicCriteriaInterfacehaving( mixed$having )Adds the having clause to the criteriapublicCriteriaInterfaceinWhere(string$expr,array$values)Appends an IN condition to the current conditionspublicCriteriaInterfaceinnerJoin(string$model,mixed$conditions = null,mixed$alias = null)Adds an INNER join to the querypublicCriteriaInterfacejoin(string$model,mixed$conditions = null,mixed$alias = null,mixed$type = null)Adds an INNER join to the querypublicCriteriaInterfaceleftJoin(string$model,mixed$conditions = null,mixed$alias = null)Adds a LEFT join to the querypublicCriteriaInterfacelimit(int$limit,int$offset = 0)Adds the limit parameter to the criteria.publicCriteriaInterfacenotBetweenWhere(string$expr,mixed$minimum,mixed$maximum)Appends a NOT BETWEEN condition to the current conditionspublicCriteriaInterfacenotInWhere(string$expr,array$values)Appends a NOT IN condition to the current conditionspublicCriteriaInterfaceorWhere(string$conditions,mixed$bindParams = null,mixed$bindTypes = null)Appends a condition to the current conditions using an OR operatorpublicCriteriaInterfaceorderBy( string$orderColumns )Adds the order-by clause to the criteriapublicCriteriaInterfacerightJoin(string$model,mixed$conditions = null,mixed$alias = null)Adds a RIGHT join to the querypublicvoidsetDI( DiInterface$container )Sets the DependencyInjector containerpublicCriteriaInterfacesetModelName( string$modelName )Set a model on which the query will be executedpublicCriteriaInterfacesharedLock( bool$sharedLock = true )Adds the "shared_lock" parameter to the criteriapublicCriteriaInterfacewhere(string$conditions,mixed$bindParams = null,mixed$bindTypes = null)Sets the conditions parameter in the criteria

Properties

protectedarray$bindParams
protectedarray$bindTypes
protectedint$hiddenParamNumber = 0
protectedstring|null$model = null
protectedarray$params = []

Methods

Public · 39

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

eager()

public function eager( array $paths ): Criteria;

Pre-loads the named relations when the criteria is executed

$invoices = Invoices::query()
    ->eager(["customer"])
    ->where("inv_total > 100")
    ->execute();

execute() forwards the parameters to Model::find(), which owns the loading, so this is a pass-through and takes the same shape: an array of dot-delimited relation paths, optionally path => options.

Returns the concrete criteria rather than the interface because the method is deliberately not part of CriteriaInterface - adding it there would break every userland implementation.

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

InterfaceSource on GitHub

Phalcon\Mvc\Model\CriteriaInterface

Interface for Phalcon\Mvc\Model\Criteria

  • Phalcon\Mvc\Model\CriteriaInterface

Uses Phalcon\Di\DiInterface

Method Summary

publicCriteriaInterfaceandWhere(string$conditions,mixed$bindParams = null,mixed$bindTypes = null)Appends a condition to the current conditions using an AND operatorpublicCriteriaInterfacebetweenWhere(string$expr,mixed$minimum,mixed$maximum)Appends a BETWEEN condition to the current conditionspublicCriteriaInterfacebind( array$bindParams )Sets the bound parameters in the criteriapublicCriteriaInterfacebindTypes( array$bindTypes )Sets the bind types in the criteriapublicCriteriaInterfacecache( array$cache )Sets the cache options in the criteriapublicCriteriaInterfaceconditions( string$conditions )Adds the conditions parameter to the criteriapublicCriteriaInterfacedistinct( mixed$distinct )Sets SELECT DISTINCT / SELECT ALL flagpublicResultsetInterfaceexecute()Executes a find using the parameters built with the criteriapublicCriteriaInterfaceforUpdate( bool$forUpdate = true )Sets the "for_update" parameter to the criteriapublicstring|array|nullgetColumns()Returns the columns to be queriedpublicstring|nullgetConditions()Returns the conditions parameter in the criteriapublicgetGroupBy()Returns the group clause in the criteriapublicgetHaving()Returns the having clause in the criteriapublicint|array|nullgetLimit()Returns the limit parameter in the criteria, which will bepublicstringgetModelName()Returns an internal model name on which the criteria will be appliedpublicstring|nullgetOrderBy()Returns the order parameter in the criteriapublicarraygetParams()Returns all the parameters defined in the criteriapublicstring|nullgetWhere()Returns the conditions parameter in the criteriapublicCriteriaInterfacegroupBy( mixed$group )Adds the group-by clause to the criteriapublicCriteriaInterfacehaving( mixed$having )Adds the having clause to the criteriapublicCriteriaInterfaceinWhere(string$expr,array$values)Appends an IN condition to the current conditionspublicCriteriaInterfaceinnerJoin(string$model,mixed$conditions = null,mixed$alias = null)Adds an INNER join to the querypublicCriteriaInterfaceleftJoin(string$model,mixed$conditions = null,mixed$alias = null)Adds a LEFT join to the querypublicCriteriaInterfacelimit(int$limit,int$offset = 0)Sets the limit parameter to the criteriapublicCriteriaInterfacenotBetweenWhere(string$expr,mixed$minimum,mixed$maximum)Appends a NOT BETWEEN condition to the current conditionspublicCriteriaInterfacenotInWhere(string$expr,array$values)Appends a NOT IN condition to the current conditionspublicCriteriaInterfaceorWhere(string$conditions,mixed$bindParams = null,mixed$bindTypes = null)Appends a condition to the current conditions using an OR operatorpublicCriteriaInterfaceorderBy( string$orderColumns )Adds the order-by parameter to the criteriapublicCriteriaInterfacerightJoin(string$model,mixed$conditions = null,mixed$alias = null)Adds a RIGHT join to the querypublicCriteriaInterfacesetModelName( string$modelName )Set a model on which the query will be executedpublicCriteriaInterfacesharedLock( bool$sharedLock = true )Sets the "shared_lock" parameter to the criteriapublicCriteriaInterfacewhere(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\Eager\Loader

ClassSource on GitHub

Loads model relations in bulk - a bounded number of queries per relation node rather than one per record - and applies the result to records as they are hydrated.

  • Phalcon\Mvc\Model\Eager\Loader

Uses Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Exceptions\EagerRowLimitExceeded · Phalcon\Mvc\Model\Exceptions\MissingEagerKeyColumn · Phalcon\Mvc\Model\Exceptions\UnknownEagerRelation · Phalcon\Mvc\Model\Manager · Phalcon\Mvc\Model\ManagerInterface · Phalcon\Mvc\Model\Relation · Phalcon\Mvc\Model\RelationInterface · Phalcon\Mvc\Model\Resultset\Simple

Method Summary

Constants

intMAX_ROWS_PER_LEVEL = 100000Maximum number of rows a single relation node may return before the load is refused. Guards against a to-many hop that follows a to-one hop, which can fan out to an entire table.

Properties

protectedManagerInterface$manager

Methods

Public · 4

__construct()

public function __construct( ManagerInterface $manager );

apply()

public static function apply(
    mixed $record,
    array $eagerMap
): void;

Applies a pre-built eager map to a single record.

Shared by Resultset\Simple::current(), which stamps records as they are hydrated, and by the loader itself, which stamps instances it retains.

Both Model and Row implement readAttribute(), so key extraction is uniform; only the write differs. A Row is what a column-restricted select produces, and it has no relation cache.

buildKey()

public static function buildKey( array $values ): string;

Builds the lookup key for a set of key-field values.

Always a string. A single value is cast, which also neutralizes the PostgreSQL-integer / MySQL-string mismatch for the same column. Multiple values are length-prefixed so [“a|b”, “c”] cannot collide with [“a”, “b|c”].

loadResultset()

public function loadResultset(
    Simple $resultset,
    string $modelName,
    array $tree
): void;

Loads a relation tree for a root resultset.

The resultset is materialized first: at this point the statement has run but no row has been consumed, so fetching every row costs nothing extra and gives the key values without a second pass over the cursor.

Protected · 7

buildMap()

protected function buildMap(
    array $parents,
    string $modelName,
    array $tree
): array;

Builds one level of the map.

buildNode()

protected function buildNode(
    RelationInterface $relation,
    string $alias,
    array $parents,
    array $node
): array;

Builds a single map node: one query, indexed by the referenced field.

buildThroughNode()

protected function buildThroughNode(
    RelationInterface $relation,
    string $alias,
    array $parents,
    array $node
): array;

Through-relations in two steps rather than a join.

Step one fetches (parentKey, referencedKey) pairs from the intermediate model; step two fetches the referenced rows for the keys those pairs collected. The pairs then attribute referenced rows back to parents without a synthetic column in the select list, and without the row multiplication an inner join would cause.

collectKeys()

protected function collectKeys(
    array $parents,
    array $fields,
    string $alias
): array;

Distinct, non-null local key tuples across the parent set.

fetchReferenced()

protected function fetchReferenced(
    RelationInterface $relation,
    string $alias,
    array $keys,
    array $options
): Simple;

One query per relation node. An empty key set issues none at all - WHERE IN () is a syntax error and there is nothing to attribute.

normalizeFields()

protected function normalizeFields( mixed $fields ): array;

Relation fields are declared as a string for a single column and an array for a composite key. Normalizing removes that fork everywhere downstream.

recordKey()

protected function recordKey(
    mixed $record,
    array $fields
): string;

Lookup key for an already-hydrated record.

Mvc\Model\Eager\PathTree

ClassSource on GitHub

Turns the eager find parameter into a tree.

Elements are either a bare path string or path => options. A path implies every one of its prefixes and prefixes are merged, so [“customer”, “customer.country”] and [“customer.country”] produce the same two-node tree. The number of queries an eager load costs follows the number of nodes in this tree, not the number of elements supplied.

  • Phalcon\Mvc\Model\Eager\PathTree

Uses Phalcon\Mvc\Model\Exceptions\InvalidEagerPath · Phalcon\Mvc\Model\Exceptions\UnsupportedEagerOption

Method Summary

Constants

intMAX_DEPTH = 5Longest path accepted. Depth alone is not what makes an eager load expensive, but an unbounded path is never intentional.

Methods

Public · 1

parse()

public static function parse( array $spec ): array;

Mvc\Model\Exception

ClassSource on GitHub

Phalcon\Mvc\Model\Exception

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

Mvc\Model\Exceptions\BelongsToRequiresObject

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\BindTypeNotDefined

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\CannotResolveAttribute

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\ColumnNotInMap

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\ColumnNotInTableColumns

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\ColumnNotInTableMap

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\CorruptColumnType

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\CursorIsImmutable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\DataTypeNotDefined

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\EagerRowLimitExceeded

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct(
    string $modelName,
    int $rowCount,
    int $limit
);

Mvc\Model\Exceptions\HandlerMustImplementBindable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\IdentityNotInColumnMap

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\IdentityNotInTableColumns

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\IndexNotInCursor

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\IndexNotInRow

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidConnectionService

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidContainer

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidDumpResultKey

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidEagerParameter

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidEagerPath

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $path );

Mvc\Model\Exceptions\InvalidFindParameters

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidGetModelNameReturn

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidModelName

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidModelsManagerService

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidModelsMetadataService

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\InvalidResultsetCacheService

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidReturnedRecord

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\InvalidSerializationData

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\ManagerOrmServicesUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\MethodNotFound

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\MissingEagerKeyColumn

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\MissingMethodName

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\MissingModelClassName

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $paramKey );

Mvc\Model\Exceptions\ModelCouldNotLoad

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $modelName );

Mvc\Model\Exceptions\ModelOrmServicesUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\PrimaryKeyRequired

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\PropertyNotAccessible

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\RecordCannotRefresh

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\RecordNotPersisted

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\ReferencedFieldsMismatch

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\RelationRequiresObjectOrArray

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\ResultsetColumnNotInMap

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Model\Exceptions\RowIsImmutable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\SnapshotsDisabled

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\StaticMethodRequiresOneArgument

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\UnknownEagerRelation

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\Exceptions\UnknownRelationType

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\UnsupportedEagerHydration

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Exceptions\UnsupportedEagerOption

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $option );

Mvc\Model\Exceptions\UnsupportedEagerResultset

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Exceptions\UpdateSnapshotDisabled

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Hydration\CaseInsensitiveColumnMap

ClassSource on GitHub
  • Phalcon\Mvc\Model\Hydration\CaseInsensitiveColumnMap

Method Summary

Methods

Public · 1

caseInsensitiveColumnMap()

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

Attempts to find key case-insensitively

Mvc\Model\Hydration\CloneResultMapHydrate

ClassSource on GitHub
  • Phalcon\Mvc\Model\Hydration\CloneResultMapHydrate

Uses Phalcon\Mvc\Model · 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"
);

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

Mvc\Model\Manager

ClassSource 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 cachepublicvoidaddBehavior(ModelInterface$model,BehaviorInterface$behavior)Binds a behavior to a modelpublicRelationInterfaceaddBelongsTo(ModelInterface$model,mixed$fields,string$referencedModel,mixed$referencedFields,array$options = [])Setup a relation reverse many to one between two modelspublicRelationInterfaceaddHasMany(ModelInterface$model,mixed$fields,string$referencedModel,mixed$referencedFields,array$options = [])Setup a relation 1-n between two modelspublicRelationInterfaceaddHasManyToMany(ModelInterface$model,mixed$fields,string$intermediateModel,mixed$intermediateFields,mixed$intermediateReferencedFields,string$referencedModel,mixed$referencedFields,array$options = [])Setups a relation n-m between two modelspublicRelationInterfaceaddHasOne(ModelInterface$model,mixed$fields,string$referencedModel,mixed$referencedFields,array$options = [])Setup a 1-1 relation between two modelspublicRelationInterfaceaddHasOneThrough(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 modelpublicvoidclearReusableObjects()Clears the internal reusable listpublicBuilderInterfacecreateBuilder( mixed$params = null )Creates a Phalcon\Mvc\Model\Query\BuilderpublicQueryInterfacecreateQuery( string$phql )Creates a Phalcon\Mvc\Model\Query without execute itpublicmixedexecuteQuery(string$phql,mixed$placeholders = null,mixed$types = null)Creates a Phalcon\Mvc\Model\Query and execute itpublicboolexistsBelongsTo(string$modelName,string$modelRelation)Checks whether a model has a belongsTo relation with another modelpublicboolexistsHasMany(string$modelName,string$modelRelation)Checks whether a model has a hasMany relation with another modelpublicboolexistsHasManyToMany(string$modelName,string$modelRelation)Checks whether a model has a hasManyToMany relation with another modelpublicboolexistsHasOne(string$modelName,string$modelRelation)Checks whether a model has a hasOne relation with another modelpublicboolexistsHasOneThrough(string$modelName,string$modelRelation)Checks whether a model has a hasOneThrough relation with another modelpublicRelationInterface[]|arraygetBelongsTo( ModelInterface$model )Gets all the belongsTo relations defined in a modelpublicResultsetInterface|boolgetBelongsToRecords(string$modelName,string$modelRelation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Gets belongsTo related records from a modelpublicBuilderInterface|nullgetBuilder()Returns the newly created Phalcon\Mvc\Model\Query\Builder or nullpublicstringgetConnectionService(ModelInterface$model,array$connectionServices)Returns the connection service name used to read or write data related topublicEventsManagerInterface|nullgetCustomEventsManager( ModelInterface$model )Returns a custom events manager related to a model or null if there ispublicDiInterfacegetDI()Returns the DependencyInjector containerpublicEventsManagerInterface|nullgetEventsManager()Returns the internal event managerpublicRelationInterface[]|arraygetHasMany( ModelInterface$model )Gets hasMany relations defined on a modelpublicResultsetInterface|boolgetHasManyRecords(string$modelName,string$modelRelation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Gets hasMany related records from a modelpublicRelationInterface[]|arraygetHasManyToMany( ModelInterface$model )Gets hasManyToMany relations defined on a modelpublicarraygetHasOne( ModelInterface$model )Gets hasOne relations defined on a modelpublicRelationInterface[]getHasOneAndHasMany( ModelInterface$model )Gets hasOne relations defined on a modelpublicModelInterface|boolgetHasOneRecords(string$modelName,string$modelRelation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Gets belongsTo related records from a modelpublicRelationInterface[]|arraygetHasOneThrough( ModelInterface$model )Gets hasOneThrough relations defined on a modelpublicModelInterface|nullgetLastInitialized()Get last initialized modelpublicQueryInterfacegetLastQuery()Returns the last query created or executed in the models managerpublicstringgetModelPrefix()Returns the prefix for all model sources.publicstring|nullgetModelSchema( ModelInterface$model )Returns the mapped schema for a modelpublicstringgetModelSource( ModelInterface$model )Returns the mapped source for a modelpublicAdapterInterfacegetReadConnection( ModelInterface$model )Returns the connection to read data related to a modelpublicstringgetReadConnectionService( ModelInterface$model )Returns the connection service name used to read data related to a modelpublicRelationInterface|boolgetRelationByAlias(string$modelName,string$alias)Returns a relation by its aliaspublicgetRelationRecords(RelationInterface$relation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Helper method to query records based on a relation definitionpublicRelationInterface[]getRelations( string$modelName )Query all the relationships defined on a modelpublicRelationInterface[]|boolgetRelationsBetween(string$first,string$second)Query the first relationship defined between two modelspublicgetReusableRecords(string$modelName,string$key)Returns a reusable object from the internal listpublicAdapterInterfacegetWriteConnection( ModelInterface$model )Returns the connection to write data related to a modelpublicstringgetWriteConnectionService( ModelInterface$model )Returns the connection service name used to write data related to a modelpublicboolhasBelongsTo(string$modelName,string$modelRelation)Checks whether a model has a belongsTo relation with another modelpublicboolhasHasMany(string$modelName,string$modelRelation)Checks whether a model has a hasMany relation with another modelpublicboolhasHasManyToMany(string$modelName,string$modelRelation)Checks whether a model has a hasManyToMany relation with another modelpublicboolhasHasOne(string$modelName,string$modelRelation)Checks whether a model has a hasOne relation with another modelpublicboolhasHasOneThrough(string$modelName,string$modelRelation)Checks whether a model has a hasOneThrough relation with another modelpublicboolinitialize( ModelInterface$model )Initializes a model in the model managerpublicboolisInitialized( string$className )Check whether a model is already initializedpublicboolisKeepingSnapshots( ModelInterface$model )Checks if a model is keeping snapshots for the queried recordspublicboolisUsingDynamicUpdate( ModelInterface$model )Checks if a model is using dynamic update instead of all-field updatepublicboolisVisibleModelProperty(ModelInterface$model,string$property)Check whether a model property is declared as public.publicvoidkeepSnapshots(ModelInterface$model,bool$keepSnapshots)Sets if a model must keep snapshotspublicModelInterfaceload( string$modelName )Loads a model throwing an exception if it does not existpublicarraymergeFindParameters(mixed$findParamsOne,mixed$findParamsTwo)Merge two arrays of find parameterspublicmissingMethod(ModelInterface$model,string$eventName,mixed$data)Dispatch an event to the listeners and behaviorspublicnotifyEvent(string$eventName,ModelInterface$model)Receives events generated in the models and dispatches them to anpublicvoidregisterWrite( ModelInterface$model )Marks the model's write connection service as written-to for thepublicvoidremoveBehavior(ModelInterface$model,string$behaviorClass)Removes a behavior from a modelpublicvoidresetConnectionState()Clears the per-request sticky write tracking. Call this betweenpublicvoidsetConnectionService(ModelInterface$model,string$connectionService)Sets both write and read connection service for a modelpublicvoidsetCustomEventsManager(ModelInterface$model,EventsManagerInterface$eventsManager)Sets a custom events manager for a specific modelpublicvoidsetDI( DiInterface$container )Sets the DependencyInjector containerpublicvoidsetEventsManager( EventsManagerInterface$eventsManager )Sets a global events managerpublicvoidsetModelPrefix( string$prefix )Sets the prefix for all model sources.publicvoidsetModelSchema(ModelInterface$model,string$schema)Sets the mapped schema for a modelpublicvoidsetModelSource(ModelInterface$model,string$source)Sets the mapped source for a modelpublicvoidsetReadConnectionService(ModelInterface$model,string$connectionService)Sets read connection service for a modelpublicvoidsetReusableRecords(string$modelName,string$key,mixed$records)Stores a reusable record in the internal listpublicvoidsetSticky( bool$sticky )Enables or disables sticky connections. When enabled, once a model haspublicvoidsetWriteConnectionService(ModelInterface$model,string$connectionService)Sets write connection service for a modelpublicvoiduseDynamicUpdate(ModelInterface$model,bool$dynamicUpdate)Sets if a model must use dynamic update instead of the all-field updateprotectedAdapterInterfacegetConnection(ModelInterface$model,array$connectionServices)Returns the connection to read or write data related to a model

Properties

protectedarray$aliases = []
protectedarray$behaviors = []Models' behaviors
protectedarray$belongsTo = []Belongs to relations
protectedarray$belongsToSingle = []All the relationships by model
protectedBuilderInterface|null$builder = null
protectedDiInterface|null$container = null
protectedarray$customEventsManager = []
protectedarray$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.
protectedarray$dynamicUpdate = []Does the model use dynamic update, instead of updating all rows?
protectedEventsManagerInterface|null$eventsManager = null
protectedarray$hasMany = []Has many relations
protectedarray$hasManySingle = []Has many relations by model
protectedarray$hasManyToMany = []Has many-Through relations
protectedarray$hasManyToManySingle = []Has many-Through relations by model
protectedarray$hasOne = []Has one relations
protectedarray$hasOneSingle = []Has one relations by model
protectedarray$hasOneThrough = []Has one through relations
protectedarray$hasOneThroughSingle = []Has one through relations by model
protectedarray$initialized = []Mark initialized models
protectedarray$keepSnapshots = []
protectedModelInterface|null$lastInitialized = nullLast model initialized
protectedQueryInterface|null$lastQuery = nullLast query created/executed
protectedarray$modelVisibility = []
protectedstring$prefix = ""
protectedarray$readConnectionServices = []
protectedarray$reusable = []Stores a list of reusable instances
protectedarray$schemas = []
protectedarray$sources = []
protectedbool$sticky = falseWhether reads should stick to the write connection after a write has occurred during the current request cycle.
protectedarray$writeConnectionServices = []

Methods

Public · 74

__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|null $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|null $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|null $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|null $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

mergeFindParameters()

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

Merge two arrays of find parameters

The order matters. Conditions coming from key 0 or “conditions” are ANDed in argument order; bind and bindTypes are merged for the second argument only and assigned outright for the first. Pass the parameters whose bindings must survive as the second argument.

Static because it reads nothing but its arguments, and public so bulk loaders can reuse the merge instead of duplicating these semantics.

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 · 1

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.

Mvc\Model\ManagerInterface

InterfaceSource 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

publicvoidaddBehavior(ModelInterface$model,BehaviorInterface$behavior)Binds a behavior to a modelpublicRelationInterfaceaddBelongsTo(ModelInterface$model,mixed$fields,string$referencedModel,mixed$referencedFields,array$options = [])Setup a relation reverse 1-1 between two modelspublicRelationInterfaceaddHasMany(ModelInterface$model,mixed$fields,string$referencedModel,mixed$referencedFields,array$options = [])Setup a relation 1-n between two modelspublicRelationInterfaceaddHasManyToMany(ModelInterface$model,mixed$fields,string$intermediateModel,mixed$intermediateFields,mixed$intermediateReferencedFields,string$referencedModel,mixed$referencedFields,array$options = [])Setups a relation n-m between two modelspublicRelationInterfaceaddHasOne(ModelInterface$model,mixed$fields,string$referencedModel,mixed$referencedFields,array$options = [])Setup a 1-1 relation between two modelspublicRelationInterfaceaddHasOneThrough(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 tablepublicvoidclearReusableObjects()Clears the internal reusable listpublicBuilderInterfacecreateBuilder( mixed$params = null )Creates a Phalcon\Mvc\Model\Query\BuilderpublicQueryInterfacecreateQuery( string$phql )Creates a Phalcon\Mvc\Model\Query without execute itpublicmixedexecuteQuery(string$phql,mixed$placeholders = null,mixed$types = null)Creates a Phalcon\Mvc\Model\Query and execute itpublicRelationInterface[]|arraygetBelongsTo( ModelInterface$model )Gets belongsTo relations defined on a modelpublicResultsetInterface|boolgetBelongsToRecords(string$modelName,string$modelRelation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Gets belongsTo related records from a modelpublicBuilderInterface|nullgetBuilder()Returns the newly created Phalcon\Mvc\Model\Query\Builder or nullpublicRelationInterface[]|arraygetHasMany( ModelInterface$model )Gets hasMany relations defined on a modelpublicResultsetInterface|boolgetHasManyRecords(string$modelName,string$modelRelation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Gets hasMany related records from a modelpublicRelationInterface[]|arraygetHasManyToMany( ModelInterface$model )Gets hasManyToMany relations defined on a modelpublicRelationInterface[]|arraygetHasOne( ModelInterface$model )Gets hasOne relations defined on a modelpublicRelationInterface[]getHasOneAndHasMany( ModelInterface$model )Gets hasOne relations defined on a modelpublicModelInterface|boolgetHasOneRecords(string$modelName,string$modelRelation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Gets hasOne related records from a modelpublicRelationInterface[]|arraygetHasOneThrough( ModelInterface$model )Gets hasOneThrough relations defined on a modelpublicModelInterface|nullgetLastInitialized()Get last initialized modelpublicQueryInterfacegetLastQuery()Returns the last query created or executed in the models managerpublicstring|nullgetModelSchema( ModelInterface$model )Returns the mapped schema for a modelpublicstringgetModelSource( ModelInterface$model )Returns the mapped source for a modelpublicAdapterInterfacegetReadConnection( ModelInterface$model )Returns the connection to read data related to a modelpublicstringgetReadConnectionService( ModelInterface$model )Returns the connection service name used to read data related to a modelpublicRelationInterface|boolgetRelationByAlias(string$modelName,string$alias)Returns a relation by its aliaspublicgetRelationRecords(RelationInterface$relation,ModelInterface$record,mixed$parameters = null,string|null$method = null)Helper method to query records based on a relation definitionpublicRelationInterface[]getRelations( string$modelName )Query all the relationships defined on a modelpublicRelationInterface[]|boolgetRelationsBetween(string$first,string$second)Query the relations between two modelspublicgetReusableRecords(string$modelName,string$key)Returns a reusable object from the internal listpublicAdapterInterfacegetWriteConnection( ModelInterface$model )Returns the connection to write data related to a modelpublicstringgetWriteConnectionService( ModelInterface$model )Returns the connection service name used to write data related to a modelpublicboolhasBelongsTo(string$modelName,string$modelRelation)Checks whether a model has a belongsTo relation with another modelpublicboolhasHasMany(string$modelName,string$modelRelation)Checks whether a model has a hasMany relation with another modelpublicboolhasHasManyToMany(string$modelName,string$modelRelation)Checks whether a model has a hasManyToMany relation with another modelpublicboolhasHasOne(string$modelName,string$modelRelation)Checks whether a model has a hasOne relation with another modelpublicboolhasHasOneThrough(string$modelName,string$modelRelation)Checks whether a model has a hasOneThrough relation with another modelpublicinitialize( ModelInterface$model )Initializes a model in the model managerpublicboolisInitialized( string$className )Check of a model is already initializedpublicboolisKeepingSnapshots( ModelInterface$model )Checks if a model is keeping snapshots for the queried recordspublicboolisUsingDynamicUpdate( ModelInterface$model )Checks if a model is using dynamic update instead of all-field updatepublicboolisVisibleModelProperty(ModelInterface$model,string$property)Check whether a model property is declared as public.publicvoidkeepSnapshots(ModelInterface$model,bool$keepSnapshots)Sets if a model must keep snapshotspublicModelInterfaceload( string$modelName )Loads a model throwing an exception if it does not existpublicmissingMethod(ModelInterface$model,string$eventName,mixed$data)Dispatch an event to the listeners and behaviorspublicnotifyEvent(string$eventName,ModelInterface$model)Receives events generated in the models and dispatches them to an events-manager if availablepublicvoidregisterWrite( ModelInterface$model )Marks the model's write connection service as written-to for thepublicvoidremoveBehavior(ModelInterface$model,string$behaviorClass)Removes a behavior from a modelpublicvoidresetConnectionState()Clears the per-request sticky write trackingpublicvoidsetConnectionService(ModelInterface$model,string$connectionService)Sets both write and read connection service for a modelpublicvoidsetModelSchema(ModelInterface$model,string$schema)Sets the mapped schema for a modelpublicvoidsetModelSource(ModelInterface$model,string$source)Sets the mapped source for a modelpublicvoidsetReadConnectionService(ModelInterface$model,string$connectionService)Sets read connection service for a modelpublicvoidsetReusableRecords(string$modelName,string$key,mixed$records)Stores a reusable record in the internal listpublicvoidsetSticky( bool$sticky )Enables or disables sticky connectionspublicsetWriteConnectionService(ModelInterface$model,string$connectionService)Sets write connection service for a modelpublicvoiduseDynamicUpdate(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|null $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|null $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|null $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|null $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

AbstractSource 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

publicCacheAdapterInterface|nullgetAdapter()Return the internal cache adapterpublicarraygetAttributes( ModelInterface$model )Returns table attributes names (fields)publicarraygetAutomaticCreateAttributes( ModelInterface$model )Returns attributes that must be ignored from the INSERT SQL generationpublicarraygetAutomaticUpdateAttributes( ModelInterface$model )Returns attributes that must be ignored from the UPDATE SQL generationpublicarraygetBindTypes( ModelInterface$model )Returns attributes and their bind data typespublicarray|nullgetColumnMap( ModelInterface$model )Returns the column map if anypublicstring|nullgetColumnMapUniqueKey( ModelInterface$model )Returns a ColumnMap Unique key for meta-data is created using classNamepublicDiInterfacegetDI()Returns the DependencyInjector containerpublicarraygetDataTypes( ModelInterface$model )Returns attributes and their data typespublicarraygetDataTypesNumeric( ModelInterface$model )Returns attributes which types are numericalpublicarraygetDefaultValues( ModelInterface$model )Returns attributes (which have default values) and their default valuespublicarraygetEmptyStringAttributes( ModelInterface$model )Returns attributes allow empty stringspublicbool|string|nullgetIdentityField( ModelInterface$model )Returns the name of identity field (if one is present)publicstring|nullgetMetaDataUniqueKey( ModelInterface$model )Returns a MetaData Unique key for meta-data is created using classNamepublicstring|nullgetModelUUID(ModelInterface$model,array$row)Returns the model UniqueID based on model and array row primary key(s) value(s)publicarraygetNonPrimaryKeyAttributes( ModelInterface$model )Returns an array of fields which are not part of the primary keypublicarraygetNotNullAttributes( ModelInterface$model )Returns an array of not null attributespublicarraygetPrimaryKeyAttributes( ModelInterface$model )Returns an array of fields which are part of the primary keypublicarray|nullgetReverseColumnMap( ModelInterface$model )Returns the reverse column map if anypublicStrategyInterfacegetStrategy()Return the strategy to obtain the meta-datapublicboolhasAttribute(ModelInterface$model,string$attribute)Check if a model has certain attributepublicboolisEmpty()Checks if the internal meta-data container is emptypublicboolmodelEquals(ModelInterface$first,ModelInterface$other)Compares if two models are the same in memorypublicarray|nullread( mixed$key )Reads metadata from the adapterpublicarray|nullreadColumnMap( ModelInterface$model )Reads the ordered/reversed column map for certain modelpublicarray|nullreadColumnMapIndex(ModelInterface$model,int$index)Reads column-map information for certain model using a MODEL_* constantpublicarray|nullreadMetaData( ModelInterface$model )Reads the complete meta-data for certain modelpublicarray|string|nullreadMetaDataIndex(ModelInterface$model,int$index)Reads meta-data for certain modelpublicvoidreset()Resets internal meta-data in order to regenerate itpublicvoidsetAutomaticCreateAttributes(ModelInterface$model,array$attributes)Set the attributes that must be ignored from the INSERT SQL generationpublicvoidsetAutomaticUpdateAttributes(ModelInterface$model,array$attributes)Set the attributes that must be ignored from the UPDATE SQL generationpublicvoidsetDI( DiInterface$container )Sets the DependencyInjector containerpublicvoidsetEmptyStringAttributes(ModelInterface$model,array$attributes)Set the attributes that allow empty string valuespublicvoidsetStrategy( StrategyInterface$strategy )Set the meta-data extraction strategypublicvoidwrite(string$key,array$data)Writes the metadata to adapterpublicvoidwriteMetaDataIndex(ModelInterface$model,int$index,mixed$data)Writes meta-data for certain model using a MODEL_* constantprotectedinitialize(ModelInterface$model,mixed$key,mixed$table,mixed$schema)Initialize old behavior for compatabilityprotectedboolinitializeColumnMap(ModelInterface$model,mixed$key)Initialize ColumnMap for a certain tableprotectedboolinitializeMetaData(ModelInterface$model,mixed$key)Initialize the metadata for certain table

Constants

intMODELS_ATTRIBUTES = 0
intMODELS_AUTOMATIC_DEFAULT_INSERT = 10
intMODELS_AUTOMATIC_DEFAULT_UPDATE = 11
intMODELS_COLUMN_MAP = 0
intMODELS_DATA_TYPES = 4
intMODELS_DATA_TYPES_BIND = 9
intMODELS_DATA_TYPES_NUMERIC = 5
intMODELS_DATE_AT = 6
intMODELS_DATE_IN = 7
intMODELS_DEFAULT_VALUES = 12
intMODELS_EMPTY_STRING_VALUES = 13
intMODELS_IDENTITY_COLUMN = 8
intMODELS_NON_PRIMARY_KEY = 2
intMODELS_NOT_NULL = 3
intMODELS_PRIMARY_KEY = 1
intMODELS_REVERSE_COLUMN_MAP = 1

Properties

protectedCacheAdapterInterface|null$adapter = null
protectedarray$columnMap = []
protectedDiInterface|null$container = null
protectedarray$metaData = []
protectedarray$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.
protectedStrategyInterface|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 behavior 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

InterfaceSource 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

publicarraygetAttributes( ModelInterface$model )Returns table attributes names (fields)publicarraygetAutomaticCreateAttributes( ModelInterface$model )Returns attributes that must be ignored from the INSERT SQL generationpublicarraygetAutomaticUpdateAttributes( ModelInterface$model )Returns attributes that must be ignored from the UPDATE SQL generationpublicarraygetBindTypes( ModelInterface$model )Returns attributes and their bind data typespublicarray|nullgetColumnMap( ModelInterface$model )Returns the column map if anypublicarraygetDataTypes( ModelInterface$model )Returns attributes and their data typespublicarraygetDataTypesNumeric( ModelInterface$model )Returns attributes which types are numericalpublicarraygetDefaultValues( ModelInterface$model )Returns attributes (which have default values) and their default valuespublicarraygetEmptyStringAttributes( ModelInterface$model )Returns attributes allow empty stringspublicbool|string|nullgetIdentityField( ModelInterface$model )Returns the name of identity field (if one is present)publicarraygetNonPrimaryKeyAttributes( ModelInterface$model )Returns an array of fields which are not part of the primary keypublicarraygetNotNullAttributes( ModelInterface$model )Returns an array of not null attributespublicarraygetPrimaryKeyAttributes( ModelInterface$model )Returns an array of fields which are part of the primary keypublicarray|nullgetReverseColumnMap( ModelInterface$model )Returns the reverse column map if anypublicStrategyInterfacegetStrategy()Return the strategy to obtain the meta-datapublicboolhasAttribute(ModelInterface$model,string$attribute)Check if a model has certain attributepublicboolisEmpty()Checks if the internal meta-data container is emptypublicarray|nullread( string$key )Reads meta-data from the adapterpublicarray|nullreadColumnMap( ModelInterface$model )Reads the ordered/reversed column map for certain modelpublicarray|nullreadColumnMapIndex(ModelInterface$model,int$index)Reads column-map information for certain model using a MODEL_* constantpublicarray|nullreadMetaData( ModelInterface$model )Reads meta-data for certain modelpublicarray|string|nullreadMetaDataIndex(ModelInterface$model,int$index)Reads meta-data for certain model using a MODEL_* constantpublicreset()Resets internal meta-data in order to regenerate itpublicsetAutomaticCreateAttributes(ModelInterface$model,array$attributes)Set the attributes that must be ignored from the INSERT SQL generationpublicsetAutomaticUpdateAttributes(ModelInterface$model,array$attributes)Set the attributes that must be ignored from the UPDATE SQL generationpublicvoidsetEmptyStringAttributes(ModelInterface$model,array$attributes)Set the attributes that allow empty string valuespublicsetStrategy( StrategyInterface$strategy )Set the meta-data extraction strategypublicvoidwrite(string$key,array$data)Writes meta-data to the adapterpublicwriteMetaDataIndex(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

ClassSource 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|null $options = null
);

Phalcon\Mvc\Model\MetaData\Apcu constructor

Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\ContainerRequired

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\CorruptedMetaData

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\InvalidContainer

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $modelName );

Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $message );

Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\MetaData\Exceptions\TableNotInDatabase

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

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

Mvc\Model\MetaData\Libmemcached

ClassSource 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

ClassSource 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

ClassSource 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

ClassSource 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

ClassSource 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

InterfaceSource 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

ClassSource 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

protectedstring$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

ClassSource 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\Cache\CacheInterface · 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|null$phql = null,DiInterface|null$container = null,array$options = [])Phalcon\Mvc\Model\Query constructorpublicQueryInterfacecache( array$cacheOptions )Sets the cache parameters of the querypublicvoidclean()Destroys the internal PHQL cachepublicexecute(array$bindParams = [],array$bindTypes = [])Executes a parsed PHQL statementpublicarraygetBindParams()Returns default bind paramspublicarraygetBindTypes()Returns default bind typespublicAdapterInterfacegetCache()Returns the current cache backend instancepublicarraygetCacheOptions()Returns the current cache optionspublicDiInterfacegetDI()Returns the dependency injection containerpublicarraygetIntermediate()Returns the intermediate representation of the PHQL statementpublicstringgetResultsetRowClass()Returns the class that will be used to hydrate rows that are not mappedpublicModelInterfacegetSingleResult(array$bindParams = [],array$bindTypes = [])Executes the query returning the first resultpublicarraygetSql()Returns an associative array with the SQL to be generated by the internal PHQL,publicTransactionInterface|nullgetTransaction()publicintgetType()Gets the type of PHQL statement executedpublicboolgetUniqueRow()Check if the query is programmed to get only the first row in thepublicarrayparse()Parses the intermediate code produced by Phalcon\Mvc\Model\Query\LangpublicQueryInterfacesetBindParams(array$bindParams,bool$merge = false)Set default bind parameterspublicQueryInterfacesetBindTypes(array$bindTypes,bool$merge = false)Set default bind parameterspublicvoidsetDI( DiInterface$container )Sets the dependency injection containerpublicQueryInterfacesetIntermediate( array$intermediate )Allows to set the IR to be executedpublicQueryInterfacesetResultsetRowClass( string$resultsetRowClass )Sets the class used to hydrate rows that are not mapped to a modelpublicQueryInterfacesetSharedLock( bool$sharedLock = false )Set SHARED LOCK clausepublicQueryInterfacesetTransaction( TransactionInterface$transaction )allows to wrap a transaction around all queriespublicQueryInterfacesetType( int$type )Sets the type of PHQL statement to be executedpublicQueryInterfacesetUniqueRow( bool$uniqueRow )Tells to the query if only the first row in the resultset must beprotectedStatusInterfaceexecuteDelete(array$intermediate,array$bindParams,array$bindTypes)Executes the DELETE intermediate representation producing aprotectedStatusInterfaceexecuteInsert(array$intermediate,array$bindParams,array$bindTypes)Executes the INSERT intermediate representation producing aprotectedResultsetInterface|arrayexecuteSelect(array$intermediate,array$bindParams,array$bindTypes,bool$simulate = false)Executes the SELECT intermediate representation producing aprotectedStatusInterfaceexecuteUpdate(array$intermediate,array$bindParams,array$bindTypes)Executes the UPDATE intermediate representation producing aprotectedarraygetCallArgument( array$argument )Resolves an expression in a single call argumentprotectedarraygetCaseExpression( array$expr )Resolves an expression in a single call argumentprotectedarraygetExpression(array$expr,bool$quoting = true)Resolves an expression from its intermediate code into an arrayprotectedarraygetFunctionCall( array$expr )Resolves an expression in a single call argumentprotectedarraygetGroupClause( array$group )Returns a processed group clause for a SELECT statementprotectedarraygetJoin(ManagerInterface$manager,array$join)Resolves a JOIN clause checking if the associated models existprotectedstringgetJoinType( array$join )Resolves a JOIN typeprotectedarraygetJoins( array$select )Processes the JOINs in the query returning an internal representation forprotectedarraygetLimitClause( array$limitClause )Returns a processed limit clause for a SELECT statementprotectedarraygetMultiJoin(string$joinType,mixed$joinSource,string$modelAlias,string$joinAlias,RelationInterface$relation)Resolves joins involving many-to-many relationsprotectedarraygetOrderClause( mixed$order )Returns a processed order clause for a SELECT statementprotectedarraygetQualified( array$expr )Replaces the model's name to its source name in a qualified-nameprotectedAdapterInterfacegetReadConnection(ModelInterface$model,array|null$intermediate = null,array$bindParams = [],array$bindTypes = [])Gets the read connection from the model if there is no transaction setprotectedResultsetInterfacegetRelatedRecords(ModelInterface$model,array$intermediate,array$bindParams,array$bindTypes)Query the records on which the UPDATE/DELETE operation will be doneprotectedarraygetSelectColumn( array$column )Resolves a column from its intermediate representation into an arrayprotectedarraygetSingleJoin(string$joinType,mixed$joinSource,string$modelAlias,string$joinAlias,RelationInterface$relation)Resolves joins involving has-one/belongs-to/has-many relationsprotectedgetTable(ManagerInterface$manager,array$qualifiedName)Resolves a table in a SELECT statement checking if the model existsprotectedAdapterInterfacegetWriteConnection(ModelInterface$model,array|null$intermediate = null,array$bindParams = [],array$bindTypes = [])Gets the write connection from the model if there is no transactionprotectedarrayprepareDelete()Analyzes a DELETE intermediate code and produces an array to be executedprotectedarrayprepareInsert()Analyzes an INSERT intermediate code and produces an array to be executedprotectedarrayprepareSelect(mixed$ast = null,bool$merge = false)Analyzes a SELECT intermediate code and produces an array to be executed laterprotectedarrayprepareUpdate()Analyzes an UPDATE intermediate code and produces an array to be executedprotectedarrayrefreshSchemasInIntermediate( array$irPhql )Refreshes the schema/source of every model referenced in a cached

Constants

intTYPE_DELETE = 303
intTYPE_INSERT = 306
intTYPE_SELECT = 309
intTYPE_UPDATE = 300

Properties

protectedarray$ast
protectedarray$bindParams = []
protectedarray$bindTypes = []
protectedmixed|null$cache = null
protectedarray|null$cacheOptions
protectedDiInterface|null$container = null
protectedbool$enableImplicitJoins
protectedarray$intermediate
protectedarray|null$internalPhqlCache
protected\Phalcon\Mvc\Model\ManagerInterface|null$manager = null
protected\Phalcon\Mvc\Model\MetaDataInterface|null$metaData = null
protectedarray$models = []
protectedarray$modelsInstances = []
protectedint$nestingLevel = -1
protectedstring|null$phql = null
protectedstring$resultsetRowClass = ""
protectedbool$sharedLock = false
protectedarray$sqlAliases = []
protectedarray$sqlAliasesModels = []
protectedarray$sqlAliasesModelsInstances = []
protectedarray$sqlColumnAliases = []
protectedarray$sqlModelsAliases = []
protectedTransactionInterface|null$transaction = nullTransactionInterface 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
protectedint|null$type
protectedbool$uniqueRow = false

Methods

Public · 26

__construct()

public function __construct(
    string|null $phql = null,
    DiInterface|null $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|null $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|null $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

InterfaceSource 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

ClassSource 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\Query · 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|null$container = null)Phalcon\Mvc\Model\Query\Builder constructorpublicBuilderInterfaceaddFrom(string$model,string|null$alias = null)Add a model to take part of the querypublicBuilderInterfaceandHaving(string$conditions,array$bindParams = [],array$bindTypes = [])Appends a condition to the current HAVING conditions clause using a AND operatorpublicBuilderInterfaceandWhere(string$conditions,array$bindParams = [],array$bindTypes = [])Appends a condition to the current WHERE conditions using a AND operatorpublicstringautoescape( string$identifier )Automatically escapes identifiers but only if they need to be escaped.publicBuilderInterfacebetweenHaving(string$expr,mixed$minimum,mixed$maximum,string$operator = BuilderInterface::OPERATOR_AND)Appends a BETWEEN condition to the current HAVING conditions clausepublicBuilderInterfacebetweenWhere(string$expr,mixed$minimum,mixed$maximum,string$operator = BuilderInterface::OPERATOR_AND)Appends a BETWEEN condition to the current WHERE conditionspublicBuilderInterfacecolumns( mixed$columns )Sets the columns to be queried. The columns can be either a string orpublicBuilderInterfacedistinct( mixed$distinct )Sets SELECT DISTINCT / SELECT ALL flagpublicBuilderInterfaceforUpdate( bool$forUpdate )Sets a FOR UPDATE clausepublicBuilderInterfacefrom( mixed$models )Sets the models who makes part of the querypublicarraygetBindParams()Returns default bind paramspublicarraygetBindTypes()Returns default bind typespublicgetColumns()Return the columns to be queriedpublicDiInterfacegetDI()Returns the DependencyInjector containerpublicboolgetDistinct()Returns SELECT DISTINCT / SELECT ALL flagpublicgetFrom()Return the models who makes part of the querypublicarraygetGroupBy()Returns the GROUP BY clausepublicstring|nullgetHaving()Return the current having clausepublicarraygetJoins()Return join parts of the querypublicgetLimit()Returns the current LIMIT clausepublicstring|array|nullgetModels()Returns the models involved in the querypublicintgetOffset()Returns the current OFFSET clausepublicgetOrderBy()Returns the set ORDER BY clausepublicstringgetPhql()Returns a PHQL statement built based on the builder parameterspublicQueryInterfacegetQuery()Returns the query builtpublicstringgetResultsetRowClass()Returns the class that will be used to hydrate rows that are not mappedpublicgetWhere()Return the conditions for the querypublicBuilderInterfacegroupBy( mixed$group )Sets a GROUP BY clausepublicBuilderInterfacehaving(string$conditions,array$bindParams = [],array$bindTypes = [])Sets the HAVING condition clausepublicBuilderInterfaceinHaving(string$expr,array$values,string$operator = BuilderInterface::OPERATOR_AND)Appends an IN condition to the current HAVING conditions clausepublicBuilderInterfaceinWhere(string$expr,array$values,string$operator = BuilderInterface::OPERATOR_AND)Appends an IN condition to the current WHERE conditionspublicBuilderInterfaceinnerJoin(string$model,string|null$conditions = null,string|null$alias = null)Adds an INNER join to the querypublicBuilderInterfacejoin(string$model,string|null$conditions = null,string|null$alias = null,string|null$type = null)Adds an :type: join (by default type - INNER) to the querypublicBuilderInterfaceleftJoin(string$model,string|null$conditions = null,string|null$alias = null)Adds a LEFT join to the querypublicBuilderInterfacelimit(int$limit,mixed$offset = null)Sets a LIMIT clause, optionally an offset clausepublicBuilderInterfacenotBetweenHaving(string$expr,mixed$minimum,mixed$maximum,string$operator = BuilderInterface::OPERATOR_AND)Appends a NOT BETWEEN condition to the current HAVING conditions clausepublicBuilderInterfacenotBetweenWhere(string$expr,mixed$minimum,mixed$maximum,string$operator = BuilderInterface::OPERATOR_AND)Appends a NOT BETWEEN condition to the current WHERE conditionspublicBuilderInterfacenotInHaving(string$expr,array$values,string$operator = BuilderInterface::OPERATOR_AND)Appends a NOT IN condition to the current HAVING conditions clausepublicBuilderInterfacenotInWhere(string$expr,array$values,string$operator = BuilderInterface::OPERATOR_AND)Appends a NOT IN condition to the current WHERE conditionspublicBuilderInterfaceoffset( int$offset )Sets an OFFSET clausepublicBuilderInterfaceorHaving(string$conditions,array$bindParams = [],array$bindTypes = [])Appends a condition to the current HAVING conditions clause using an OR operatorpublicBuilderInterfaceorWhere(string$conditions,array$bindParams = [],array$bindTypes = [])Appends a condition to the current conditions using an OR operatorpublicBuilderInterfaceorderBy( mixed$orderBy )Sets an ORDER BY condition clausepublicBuilderInterfacerightJoin(string$model,string|null$conditions = null,string|null$alias = null)Adds a RIGHT join to the querypublicBuilderInterfacesetBindParams(array$bindParams,bool$merge = false)Set default bind parameterspublicBuilderInterfacesetBindTypes(array$bindTypes,bool$merge = false)Set default bind typespublicvoidsetDI( DiInterface$container )Sets the DependencyInjector containerpublicBuilderInterfacesetResultsetRowClass( string$resultsetRowClass )Sets the class used to hydrate rows that are not mapped to a modelpublicBuilderInterfacewhere(string$conditions,array$bindParams = [],array$bindTypes = [])Sets the query WHERE conditionsprotectedBuilderInterfaceconditionBetween(string$clause,string$operator,string$expr,mixed$minimum,mixed$maximum)Appends a BETWEEN conditionprotectedBuilderInterfaceconditionIn(string$clause,string$operator,string$expr,array$values)Appends an IN conditionprotectedBuilderInterfaceconditionNotBetween(string$clause,string$operator,string$expr,mixed$minimum,mixed$maximum)Appends a NOT BETWEEN conditionprotectedBuilderInterfaceconditionNotIn(string$clause,string$operator,string$expr,array$values)Appends a NOT IN condition

Properties

protectedarray$bindParams = []
protectedarray$bindTypes = []
protectedarray|string|null$columns = null
protectedarray|string|null$conditions = null
protectedDiInterface|null$container
protectedmixed$distinct = null
protectedbool$forUpdate = false
protectedarray$group = []
protectedstring|null$having = null
protectedint$hiddenParamNumber = 0
protectedarray$joins = []
protectedarray|string$limit
protectedarray|string$models
protectedint$offset = 0
protectedarray|string$order
protectedstring$resultsetRowClass = ""
protectedbool$sharedLock = false

Methods

Public · 50

__construct()

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

Phalcon\Mvc\Model\Query\Builder constructor

addFrom()

public function addFrom(
    string $model,
    string|null $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",
    ]
);

Passing null (or an empty array) clears the clause; the PHQL generator treats both as “no GROUP BY”.

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|null $conditions = null,
    string|null $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|null $conditions = null,
    string|null $alias = null,
    string|null $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|null $conditions = null,
    string|null $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|null $conditions = null,
    string|null $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

InterfaceSource on GitHub

Interface for Phalcon\Mvc\Model\Query\Builder

  • Phalcon\Mvc\Model\Query\BuilderInterface

Uses Phalcon\Mvc\Model\QueryInterface

Method Summary

publicBuilderInterfaceaddFrom(string$model,string|null$alias = null)Add a model to take part of the querypublicBuilderInterfaceandWhere(string$conditions,array$bindParams = [],array$bindTypes = [])Appends a condition to the current conditions using a AND operatorpublicBuilderInterfacebetweenWhere(string$expr,mixed$minimum,mixed$maximum,string$operator = BuilderInterface::OPERATOR_AND)Appends a BETWEEN condition to the current conditionspublicBuilderInterfacecolumns( mixed$columns )Sets the columns to be queried. The columns can be either a string orpublicBuilderInterfacedistinct( mixed$distinct )Sets SELECT DISTINCT / SELECT ALL flagpublicBuilderInterfaceforUpdate( bool$forUpdate )Sets a FOR UPDATE clausepublicBuilderInterfacefrom( mixed$models )Sets the models who makes part of the querypublicarraygetBindParams()Returns default bind paramspublicarraygetBindTypes()Returns default bind typespublicgetColumns()Return the columns to be queriedpublicboolgetDistinct()Returns SELECT DISTINCT / SELECT ALL flagpublicgetFrom()Return the models who makes part of the querypublicarraygetGroupBy()Returns the GROUP BY clausepublicstring|nullgetHaving()Returns the HAVING condition clausepublicarraygetJoins()Return join parts of the querypublicgetLimit()Returns the current LIMIT clausepublicstring|array|nullgetModels()Returns the models involved in the querypublicintgetOffset()Returns the current OFFSET clausepublicgetOrderBy()Return the set ORDER BY clausepublicstringgetPhql()Returns a PHQL statement built based on the builder parameterspublicQueryInterfacegetQuery()Returns the query builtpublicgetWhere()Return the conditions for the querypublicBuilderInterfacegroupBy( mixed$group )Sets a GROUP BY clausepublicBuilderInterfacehaving(string$conditions,array$bindParams = [],array$bindTypes = [])Sets a HAVING condition clausepublicBuilderInterfaceinWhere(string$expr,array$values,string$operator = BuilderInterface::OPERATOR_AND)Appends an IN condition to the current conditionspublicBuilderInterfaceinnerJoin(string$model,string|null$conditions = null,string|null$alias = null)Adds an INNER join to the querypublicBuilderInterfacejoin(string$model,string|null$conditions = null,string|null$alias = null)Adds an :type: join (by default type - INNER) to the querypublicBuilderInterfaceleftJoin(string$model,string|null$conditions = null,string|null$alias = null)Adds a LEFT join to the querypublicBuilderInterfacelimit(int$limit,mixed$offset = null)Sets a LIMIT clausepublicBuilderInterfacenotBetweenWhere(string$expr,mixed$minimum,mixed$maximum,string$operator = BuilderInterface::OPERATOR_AND)Appends a NOT BETWEEN condition to the current conditionspublicBuilderInterfacenotInWhere(string$expr,array$values,string$operator = BuilderInterface::OPERATOR_AND)Appends a NOT IN condition to the current conditionspublicBuilderInterfaceoffset( int$offset )Sets an OFFSET clausepublicBuilderInterfaceorWhere(string$conditions,array$bindParams = [],array$bindTypes = [])Appends a condition to the current conditions using an OR operatorpublicBuilderInterfaceorderBy( mixed$orderBy )Sets an ORDER BY condition clausepublicBuilderInterfacerightJoin(string$model,string|null$conditions = null,string|null$alias = null)Adds a RIGHT join to the querypublicBuilderInterfacesetBindParams(array$bindParams,bool$merge = false)Set default bind parameterspublicBuilderInterfacesetBindTypes(array$bindTypes,bool$merge = false)Set default bind typespublicBuilderInterfacewhere(string$conditions,array$bindParams = [],array$bindTypes = [])Sets conditions for the query

Constants

stringOPERATOR_AND = "and"
stringOPERATOR_OR = "or"

Methods

Public · 38

addFrom()

public function addFrom(
    string $model,
    string|null $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|null $conditions = null,
    string|null $alias = null
): BuilderInterface;

Adds an INNER join to the query

join()

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

Adds an :type: join (by default type - INNER) to the query

leftJoin()

public function leftJoin(
    string $model,
    string|null $conditions = null,
    string|null $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|null $conditions = null,
    string|null $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

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $wildcard );

Mvc\Model\Query\Exceptions\BindTypeRequiresArray

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Model\Query\Exceptions\BindValueRequired

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $column );

Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\Builder\ModelRequired

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $operator );

Mvc\Model\Query\Exceptions\ColumnNotInDomain

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedDeleteAst

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedInsertAst

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedSelectAst

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\CorruptedUpdateAst

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\DuplicateAlias

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Model\Query\Exceptions\InsertColumnCountMismatch

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidCachedResultset

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidCachingOptions

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidColumnDefinition

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidInjectedManager

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidInjectedMetadata

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidQueryCacheService

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\InvalidResultsetClass

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\InvalidResultsetRowClass

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MissingMetaData

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MissingModelAttribute

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MixedDatabaseSystems

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\ModelSourceNotFound

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\NoModelForAlias

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $fieldName );

Mvc\Model\Query\Exceptions\ReadConnectionMissing

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\RelationshipNotFound

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\ResultsetNonCacheable

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\ResultsetRowClassNotFound

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $className );

Mvc\Model\Query\Exceptions\UnknownBindType

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UnknownColumnType

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UnknownJoinType

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UnknownPhqlStatement

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $type );

Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Exceptions\WriteConnectionMissing

ClassSource on GitHub

Uses Phalcon\Mvc\Model\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Model\Query\Lang

AbstractSource 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

ClassSource 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

protectedModelInterface|null$model
protectedbool$success

Methods

Public · 4

__construct()

public function __construct(
    bool $success,
    ModelInterface|null $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

InterfaceSource 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

ClassSource on GitHub

Phalcon\Mvc\Model\Relation

This class represents a relationship between two models

Method Summary

Constants

intACTION_CASCADE = 2
intACTION_RESTRICT = 1
intBELONGS_TO = 0
intHAS_MANY = 2
intHAS_MANY_THROUGH = 4
intHAS_ONE = 1
intHAS_ONE_THROUGH = 3
intNO_ACTION = 0

Properties

protectedarray|string$fields
protectedarray|string$intermediateFields
protectedstring|null$intermediateModel = null
protectedarray|string$intermediateReferencedFields
protectedarray$options = []
protectedarray|string$referencedFields
protectedstring$referencedModel
protectedint$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

InterfaceSource 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

InterfaceSource 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

AbstractSource 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<TKey, TValue> @implements ArrayAccess<TKey, TValue>

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 constructorpublicintcount()Counts how many rows are in the resultsetpublicbooldelete( Closure|null$conditionCallback = null )Deletes every record in the resultsetpublicModelInterface[]filter( callable$filter )Filters a resultset returning only those the developer requirespublicCacheInterface|nullgetCache()Returns the associated cache for the resultsetpublicmixed|nullgetFirst()Get first row in the resultsetpublicintgetHydrateMode()Returns the current hydration modepublicModelInterface|nullgetLast()Get last row in the resultsetpublicMessageInterface[]getMessages()Returns the error messages produced by a batch operationpublicmixedgetResult()publicintgetType()Returns the internal type of data retrieval that the resultset is usingpublicboolisFresh()Tell if the resultset if fresh or an old one cachedpublicarrayjsonSerialize()Returns serialised model objects as array for json_encode.publicint|nullkey()Gets pointer number of active row in the resultsetpublicvoidmaterialize()Fetches every remaining row of the underlying cursor into memory,publicvoidnext()Moves cursor to next row in the resultsetpublicbooloffsetExists( mixed$index )Checks whether offset exists in the resultsetpublicmixedoffsetGet( mixed$index )Gets row in a specific position of the resultsetpublicvoidoffsetSet(mixed$offset,mixed$value)Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interfacepublicvoidoffsetUnset( mixed$offset )Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interfacepublicboolrefresh()publicvoidrewind()Rewinds resultset to its beginningpublicvoidseek( mixed$position )Changes the internal pointer to a specific position in the resultset.publicResultsetInterfacesetHydrateMode( int$hydrateMode )Sets the hydration mode in the resultsetpublicResultsetInterfacesetIsFresh( bool$isFresh )Set if the resultset is fresh or an old one cachedpublicboolupdate(mixed$data,Closure|null$conditionCallback = null)Updates every record in the resultsetpublicboolvalid()Check whether internal resource has rows to fetch

Constants

intHYDRATE_ARRAYS = 1
intHYDRATE_OBJECTS = 2
intHYDRATE_RECORDS = 0
intTYPE_RESULT_FULL = 0
intTYPE_RESULT_PARTIAL = 1

Properties

protectedmixed|null$activeRow = null
protectedCacheInterface|null$cache = null
protectedint|null$count = nullNumber of rows, or null while it has not been worked out yet. Resolved lazily by count() - asking the driver up front costs SQLite an extra statement on every single result-set.
protectedarray$errorMessages = []
protectedint$hydrateMode = 0
protectedbool$isFresh = true
protectedint$pointer = 0
protectedResultInterface|bool$resultPhalcon\Db\ResultInterface or false for empty resultset
protectedmixed|null$row = null
protectedarray|null$rows = null

Methods

Public · 27

__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|null $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

materialize()

public function materialize(): void;

Fetches every remaining row of the underlying cursor into memory, turning the resultset into TYPE_RESULT_FULL.

Free when called before the cursor has been advanced: the statement has already been executed by Model\Query::executeSelect() and only the row the constructor consumed is missing from the cursor, so no re-execution takes place. Idempotent.

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|null $conditionCallback = null
): bool;

Updates every record in the resultset

valid()

public function valid(): bool;

Check whether internal resource has rows to fetch

Driven by the row the cursor is parked on rather than by the count, so that a plain traversal never has to ask the driver how many rows there are - on SQLite that answer costs a second statement.

Mvc\Model\ResultsetInterface

InterfaceSource 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|null $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|null $conditionCallback = null
): bool;

Updates every record in the resultset

Mvc\Model\Resultset\Complex

ClassSource 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

protectedarray$columnTypes
protectedbool$disableHydration = falseUnserialised result-set hydrated all rows already. unserialise() sets disableHydration to true
protectedstring$resultsetRowClass = ""

Methods

Public · 7

__construct()

public function __construct(
    mixed $columnTypes,
    ResultInterface|null $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

ClassSource 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\Eager\Loader · 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

protectedarray|string$columnMap
protectedarray|null$eagerMap = null
protectedbool$keepSnapshots = false
protectedModelInterface|Row$model

Methods

Public · 9

__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

setEagerMap()

public function setEagerMap( array $eagerMap ): void;

Attaches a pre-loaded relation map, applied to every record as it is hydrated.

Records in a resultset are transient - seek() clears activeRow on every move and current() re-hydrates from the raw row - so hydration is the only durable point at which relations can be stamped.

sliceRows()

public function sliceRows( array $indexes ): Simple;

Builds a new resultset of the same concrete class over the rows at the given positions, preserving the column map, record prototype and snapshot behavior of this resultset.

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

ClassSource 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

ClassSource 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

protectedbool$activeTransaction = false
protectedAdapterInterface$connection
protectedbool$isNewTransaction = true
protectedManagerInterface|null$manager = null
protectedarray$messages = []
protectedbool$rollbackOnAbort = false
protectedModelInterface|null$rollbackRecord = null
protectedbool$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|null $rollbackMessage = null,
    ModelInterface|null $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

InterfaceSource 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|null $rollbackMessage = null,
    ModelInterface|null $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

ClassSource on GitHub

Phalcon\Mvc\Model\Transaction\Exception

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

Mvc\Model\Transaction\Failed

ClassSource 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

protectedModelInterface|null$record = null

Methods

Public · 3

__construct()

public function __construct(
    string $message,
    ModelInterface|null $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

ClassSource 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|null$container = null )Phalcon\Mvc\Model\Transaction\Manager constructorpublicvoidcollectTransactions()Remove all the transactions from the managerpubliccommit()Commits active transactions within the managerpublicTransactionInterfaceget( bool$autoBegin = true )Returns a new \Phalcon\Mvc\Model\Transaction or an already created oncepublicDiInterfacegetDI()Returns the dependency injection containerpublicstringgetDbService()Returns the database service used to isolate the transactionpublicTransactionInterfacegetOrCreateTransaction( bool$autoBegin = true )Create/Returns a new transaction or an existing onepublicboolgetRollbackPendent()Check if the transaction manager is registering a shutdown function topublicboolhas()Checks whether the manager has an active transactionpublicvoidnotifyCommit( TransactionInterface$transaction )Notifies the manager about a committed transactionpublicvoidnotifyRollback( TransactionInterface$transaction )Notifies the manager about a rollbacked transactionpublicvoidrollback( bool$collect = true )Rollbacks active transactions within the managerpublicvoidrollbackPendent()Rollbacks active transactions within the managerpublicvoidsetDI( DiInterface$container )Sets the dependency injection containerpublicManagerInterfacesetDbService( string$service )Sets the database service used to run the isolated transactionspublicManagerInterfacesetRollbackPendent( bool$rollbackPendent )Set if the transaction manager must register a shutdown function to cleanprotectedvoidcollectTransaction( TransactionInterface$transaction )Removes transactions from the TransactionManager

Properties

protectedDiInterface|null$container
protectedbool$initialized = false
protectedint$number = 0
protectedbool$rollbackPendent = true
protectedstring$service = "db"
protectedarray$transactions = []

Methods

Public · 16

__construct()

public function __construct( DiInterface|null $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

InterfaceSource 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

ClassSource 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

protectedModelInterface$model
protectedarray$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

InterfaceSource 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|null $container = null );

Registers an autoloader related to the module

registerServices()

public function registerServices( DiInterface $container );

Registers services related to the module

Mvc\Router

ClassSource 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 constructorpublicRouteInterfaceadd(string$pattern,mixed$paths = null,mixed$httpMethods = null,int$position = Router::POSITION_LAST)Adds a route to the router without any HTTP constraintpublicRouteInterfaceaddConnect(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is CONNECTpublicRouteInterfaceaddDelete(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is DELETEpublicRouteInterfaceaddGet(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is GETpublicRouteInterfaceaddHead(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is HEADpublicRouteInterfaceaddOptions(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Add a route to the router that only match if the HTTP method is OPTIONSpublicRouteInterfaceaddPatch(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is PATCHpublicRouteInterfaceaddPost(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is POSTpublicRouteInterfaceaddPurge(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is PURGEpublicRouteInterfaceaddPut(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is PUTpublicRouteInterfaceaddTrace(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is TRACEpublicstaticattach(RouteInterface$route,int$position = Router::POSITION_LAST)Attach Route object to the routes stack.publicarraybuildDispatcherDump()Produces a pure-data array describing every piece of state neededpublicvoidclear()Removes all the pre-defined routespublicvoiddumpDispatcher( string$path )File-shaped helper around buildDispatcherDump(). Writes the dump aspublicstringgetActionName()Returns the processed action namepublicstringgetControllerName()Returns the processed controller namepublicarraygetDefaults()Returns an array of default parameterspublicManagerInterface|nullgetEventsManager()Returns the internal event managerpublicarraygetKeyRouteIds()publicarraygetKeyRouteNames()publicRouteInterface|nullgetMatchedRoute()Returns the route that matches the handled URIpublicarraygetMatches()Returns the sub expressions in the regular expression matchedpublicarraygetMethodRoutes()Returns the routes indexed by HTTP method.publicstringgetModuleName()Returns the processed module namepublicstringgetNamespaceName()Returns the processed namespace namepublicarraygetParams()Returns the processed parameterspublicstringgetRewriteUri()Get rewrite info. This info is read from $_GET["_url"].publicRouteInterface|boolgetRouteById( mixed$routeId )Returns a route object by its idpublicRouteInterface|boolgetRouteByName( string$name )Returns a route object by its namepublicRouteInterface[]getRoutes()Returns all the routes defined in the routerpublicvoidhandle( string$uri )Handles routing information received from the rewrite enginepublicboolisExactControllerName()Returns whether controller name should not be mangledpublicvoidloadDispatcher( string$path )File-shaped helper around loadDispatcherFromArray(). Includes thepublicvoidloadDispatcherFromArray( array$dump )Inverse of buildDispatcherDump(). Reconstructs every Route from thepublicstaticloadFromConfig( mixed$config )Loads routes from an array or Phalcon\Config\Config instance.publicstaticmount( GroupInterface$group )Mounts a group of routes in the routerpublicstaticnotFound( mixed$paths )Set a group of paths to be returned when none of the defined routes arepublicstaticremoveExtraSlashes( bool$remove )Set whether router must remove the extra slashes in the handled routespublicstaticsetDefaultAction( string$actionName )Sets the default action namepublicstaticsetDefaultController( string$controllerName )Sets the default controller namepublicstaticsetDefaultModule( string$moduleName )Sets the name of the default modulepublicstaticsetDefaultNamespace( string$namespaceName )Sets the name of the default namespacepublicstaticsetDefaults( array$defaults )Sets an array of default paths. If a route is missing a path the routerpublicvoidsetEventsManager( ManagerInterface$eventsManager )Sets the events managerpublicstaticsetKeyRouteIds( array$routeIds )publicstaticsetKeyRouteNames( array$routeNames )publicstaticsetUriSource( int$uriSource )Sets the URI source. One of the URI_SOURCE_* constantspublicvoiduseCache(CacheAdapterInterface$cache,string$key = "phalcon.router.dispatcher")Cache-instance convenience wrapper. On cache hit, restores thepublicboolwasMatched()Checks if the router matches any of the defined routesprotectedvoidaddRouteFromConfig( array$routeData )Adds a single route from a config array entry. Used by loadFromConfig.protectedstringextractRealUri( string$uri )protectedvoidmountGroupFromConfig( array$groupData )Builds a Group from a config entry and mounts it. Used by loadFromConfig.protectedvoidrebuildMethodIndex()Rebuilds the HTTP-method index from the current routes array.

Constants

intPOSITION_FIRST = 0
intPOSITION_LAST = 1
intREGEX_CHUNK_SIZE = 10Number of alternatives per combined-regex chunk. Empirically derived (FastRoute uses ~10) - keeps each chunk below PCRE's optimizer cliff.
intURI_SOURCE_GET_URL = 0
intURI_SOURCE_SERVER_REQUEST_URI = 1

Properties

protectedstring$action = ""
protectedarray$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.
protectedarray$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.
protectedarray$combinedRegexDisabled = []Boolean per method bucket: true when the combined regex cannot be built (hostname route present, exotic pattern shape, etc.).
protectedarray$combinedRegexMarkMap = []Map from MARK label back to the route index in candidatesByMethod[method]. One per chunk. combinedRegexMarkMap[method][chunkIdx][markLabel] = routeIdx
protectedstring$controller = ""
protectedstring$defaultAction = ""
protectedstring$defaultController = ""
protectedstring$defaultModule = ""
protectedstring$defaultNamespace = ""
protectedarray$defaultParams = []
protectedManagerInterface|null$eventsManager
protectedarray$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.
protectedarray$hostnameLessByMethod = []Per-method indices of routes without a hostname constraint, in attach order. Shape: hostnameLessByMethod[method] = list of route indices into candidatesByMethod[method].
protectedarray$keyRouteIds = []
protectedarray$keyRouteNames = []
protectedRouteInterface|null$matchedRoute = null
protectedarray$matches = []
protectedarray$methodRoutes = []
protectedbool$methodRoutesDirty = true
protectedstring$module = ""
protectedstring$namespaceName = ""
protectedarray|string|null$notFoundPaths = null
protectedarray$params = []
protectedCacheAdapterInterface|null$pendingCache = nullLazy-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.
protectedstring$pendingCacheKey = ""
protectedbool$removeExtraSlashes = false
protectedarray$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 ]
protectedarray$routes = []
protectedarray$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.
protectedarray$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).
protectedint$uriSource = self::URI_SOURCE_GET_URL
protectedbool$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;

Rebuilds the HTTP-method index from the current routes array. Routes with no HTTP method constraint are filed under “*”.

Mvc\RouterInterface

InterfaceSource on GitHub

Interface for Phalcon\Mvc\Router

  • Phalcon\Mvc\RouterInterface

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

Method Summary

publicRouteInterfaceadd(string$pattern,mixed$paths = null,mixed$httpMethods = null,int$position = Router::POSITION_LAST)Adds a route to the router on any HTTP methodpublicRouteInterfaceaddConnect(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is CONNECTpublicRouteInterfaceaddDelete(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is DELETEpublicRouteInterfaceaddGet(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is GETpublicRouteInterfaceaddHead(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is HEADpublicRouteInterfaceaddOptions(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Add a route to the router that only match if the HTTP method is OPTIONSpublicRouteInterfaceaddPatch(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is PATCHpublicRouteInterfaceaddPost(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is POSTpublicRouteInterfaceaddPurge(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is PURGEpublicRouteInterfaceaddPut(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is PUTpublicRouteInterfaceaddTrace(string$pattern,mixed$paths = null,int$position = Router::POSITION_LAST)Adds a route to the router that only match if the HTTP method is TRACEpublicRouterInterfaceattach(RouteInterface$route,int$position = Router::POSITION_LAST)Attach Route object to the routes stack.publicvoidclear()Removes all the defined routespublicstringgetActionName()Returns processed action namepublicstringgetControllerName()Returns processed controller namepublicRouteInterface|nullgetMatchedRoute()Returns the route that matches the handled URIpublicarraygetMatches()Return the sub expressions in the regular expression matchedpublicstringgetModuleName()Returns processed module namepublicstringgetNamespaceName()Returns processed namespace namepublicarraygetParams()Returns processed extra paramspublicRouteInterface|boolgetRouteById( mixed$routeId )Returns a route object by its idpublicRouteInterface|boolgetRouteByName( string$name )Returns a route object by its namepublicRouteInterface[]getRoutes()Return all the routes defined in the routerpublicvoidhandle( string$uri )Handles routing information received from the rewrite enginepublicRouterInterfaceloadFromConfig( mixed$config )Loads routes from an array or Phalcon\Config\Config instance.publicRouterInterfacemount( GroupInterface$group )Mounts a group of routes in the routerpublicRouterInterfacesetDefaultAction( string$actionName )Sets the default action namepublicRouterInterfacesetDefaultController( string$controllerName )Sets the default controller namepublicRouterInterfacesetDefaultModule( string$moduleName )Sets the name of the default modulepublicRouterInterfacesetDefaults( array$defaults )Sets an array of default pathspublicboolwasMatched()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

ClassSource 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

protectedcallable|string|null$actionPreformatCallback = null
protectedstring$actionSuffix = "Action"
protectedstring$controllerSuffix = "Controller"
protectedarray$handlers = []
protectedstring$routePrefix = ""

Methods

Public · 10

addModuleResource()

public function addModuleResource(
    string $module,
    string $handler,
    string|null $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|null $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

ClassSource on GitHub

Phalcon\Mvc\Router\Exception

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

Mvc\Router\Exceptions\AnnotationsServiceUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\BeforeMatchNotCallable

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\ConfigKeyMustBeArray

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Router\Exceptions\EmptyGroupOfRoutes

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\GroupRoutesMustBeArray

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidCallbackParameter

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidConfigSource

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidNotFoundPaths

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidRoutePaths

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidRoutePosition

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\InvalidRouterFactoryConfig

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\MissingGroupRouteKey

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Router\Exceptions\MissingRouteConfigKey

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $key );

Mvc\Router\Exceptions\RequestServiceUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Router\Exceptions\UnknownHttpMethod

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $method );

Mvc\Router\Exceptions\WrongPathsKey

ClassSource on GitHub

Uses Phalcon\Mvc\Router\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $part );

Mvc\Router\Group

ClassSource 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 constructorpublicRouteInterfaceadd(string$pattern,mixed$paths = null,mixed$httpMethods = null)Adds a route to the router on any HTTP methodpublicRouteInterfaceaddConnect(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is CONNECTpublicRouteInterfaceaddDelete(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is DELETEpublicRouteInterfaceaddGet(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is GETpublicRouteInterfaceaddHead(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is HEADpublicRouteInterfaceaddOptions(string$pattern,mixed$paths = null)Add a route to the router that only match if the HTTP method is OPTIONSpublicRouteInterfaceaddPatch(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is PATCHpublicRouteInterfaceaddPost(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is POSTpublicRouteInterfaceaddPurge(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is PURGEpublicRouteInterfaceaddPut(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is PUTpublicRouteInterfaceaddTrace(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is TRACEpublicGroupInterfacebeforeMatch( callable$beforeMatch )Sets a callback that is called if the route is matched.publicvoidclear()Removes all the pre-defined routespubliccallable|nullgetBeforeMatch()Returns the 'before match' callback if anypublicstring|nullgetHostname()Returns the hostname restrictionpublicarray|string|nullgetPaths()Returns the common paths defined for this grouppublicstring|nullgetPrefix()Returns the common prefix for all the routespublicRouteInterface[]getRoutes()Returns the routes added to the grouppublicGroupInterfacesetHostname( string$hostname )Set a hostname restriction for all the routes in the grouppublicGroupInterfacesetPaths( mixed$paths )Set common paths for all the routes in the grouppublicGroupInterfacesetPrefix( string$prefix )Set a common uri prefix for all the routes in this groupprotectedRouteInterfaceaddRoute(string$pattern,mixed$paths = null,mixed$httpMethods = null)Adds a route applying the common attributes

Properties

protectedcallable|null$beforeMatch = null
protectedstring|null$hostname = null
protectedarray|string|null$paths = null
protectedstring|null$prefix = null
protectedarray$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

InterfaceSource 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

publicRouteInterfaceadd(string$pattern,mixed$paths = null,mixed$httpMethods = null)Adds a route to the router on any HTTP methodpublicRouteInterfaceaddConnect(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is CONNECTpublicRouteInterfaceaddDelete(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is DELETEpublicRouteInterfaceaddGet(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is GETpublicRouteInterfaceaddHead(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is HEADpublicRouteInterfaceaddOptions(string$pattern,mixed$paths = null)Add a route to the router that only match if the HTTP method is OPTIONSpublicRouteInterfaceaddPatch(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is PATCHpublicRouteInterfaceaddPost(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is POSTpublicRouteInterfaceaddPurge(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is PURGEpublicRouteInterfaceaddPut(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is PUTpublicRouteInterfaceaddTrace(string$pattern,mixed$paths = null)Adds a route to the router that only match if the HTTP method is TRACEpublicGroupInterfacebeforeMatch( callable$beforeMatch )Sets a callback that is called if the route is matched.publicvoidclear()Removes all the pre-defined routespubliccallable|nullgetBeforeMatch()Returns the 'before match' callback if anypublicstring|nullgetHostname()Returns the hostname restrictionpublicarray|string|nullgetPaths()Returns the common paths defined for this grouppublicstring|nullgetPrefix()Returns the common prefix for all the routespublicRouteInterface[]getRoutes()Returns the routes added to the grouppublicGroupInterfacesetHostname( string$hostname )Set a hostname restriction for all the routes in the grouppublicGroupInterfacesetPaths( mixed$paths )Set common paths for all the routes in the grouppublicGroupInterfacesetPrefix( 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

ClassSource 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 constructorpublicRouteInterfacebeforeMatch( callable$callback )Sets a callback that is called if the route is matched.publicstringcompilePattern( string$pattern )Replaces placeholders from pattern returning a valid PCRE regular expressionpublicRouteInterfaceconvert(string$name,mixed$converter){@inheritdoc}publicarray|boolextractNamedParams( string$pattern )Extracts parameters from a stringpubliccallable|nullgetBeforeMatch()Returns the 'before match' callback if anypublicstring|nullgetCompiledHostName()Returns the compiled hostname regex, or null when the hostname ispublicstringgetCompiledPattern()Returns the route's compiled patternpublicarraygetConverters()Returns the router converterpublicGroupInterface|nullgetGroup()Returns the group associated with the routepublicstring|nullgetHostname()Returns the hostname restriction if anypublicarray|string|nullgetHttpMethods()Returns the HTTP methods that constraint matching the routepubliccallable|nullgetMatch()Returns the 'match' callback if anypublicstring|nullgetName()Returns the route's namepublicarraygetPaths()Returns the pathspublicstringgetPattern()Returns the route's patternpublicarraygetReversedPaths()Returns the paths using positions as keys and names as valuespublicstringgetRouteId()Returns the route's idpublicarraygetRoutePaths( mixed$paths = null )Returns routePathspublicRouteInterfacematch( mixed$callback )Allows to set a callback to handle the request directly in the routepublicvoidreConfigure(string$pattern,mixed$paths = null)Reconfigure the route adding a new pattern and a set of pathspublicvoidreset()Resets the internal route id generatorpublicRouteInterfacesetGroup( GroupInterface$group )Sets the group associated with the routepublicRouteInterfacesetHostname( string$hostname )Sets a hostname restriction to the routepublicRouteInterfacesetHttpMethods( mixed$httpMethods )Sets a set of HTTP methods that constraint the matching of the route (alias of via)publicRouteInterfacesetName( string$name )Sets the route's namepublicRouteInterfacesetRouteId( string$routeId )Sets the route's id. Intended for restoring cached routes - mostpublicRouteInterfacevia( mixed$httpMethods )Set one or more HTTP methods that constraint the matching of the route

Properties

protectedcallable|null$beforeMatch = null
protectedstring|null|false$compiledHostName = falseCached 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."
protectedstring|null$compiledPattern = null
protectedarray$converters = []
protectedGroupInterface|null$group = null
protectedstring|null$hostname = null
protectedcallable|null$match = null
protectedarray|string|null$methods = []
protectedstring|null$name = null
protectedarray$paths = []
protectedstring$pattern
protectedstring$routeId = ""
protectedint$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

InterfaceSource on GitHub

Interface for Phalcon\Mvc\Router\Route

  • Phalcon\Mvc\Router\RouteInterface

Method Summary

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

ClassSource 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

ClassSource 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

protectednull|string$basePath = null
protectednull|string$baseUri = null
protectedRouterInterface|null$router = null
protectednull|string$staticBaseUri = null

Methods

Public · 10

__construct()

public function __construct( RouterInterface|null $router = null );

get()

public function get(
    mixed $uri = null,
    mixed $arguments = null,
    bool|null $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",
    ]
);

// A URI that already carries a scheme is detected as remote and is
// returned untouched. The third parameter is only honored when it is
// explicitly true - a false reads the same as leaving it out.
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|null $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

ClassSource on GitHub

Phalcon\Mvc\Url\Exception

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

Mvc\Url\Exceptions\MissingRouteName

ClassSource on GitHub

Uses Phalcon\Mvc\Url\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Url\Exceptions\RouteNotFound

ClassSource on GitHub

Uses Phalcon\Mvc\Url\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $name );

Mvc\Url\Exceptions\RouterServiceUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\Url\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\Url\UrlInterface

InterfaceSource 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|null $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|null $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

ClassSource 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 constructorpublicmixed|null__get( string$key )Magic method to retrieve a variable passed to the viewpublicbool__isset( string$key )Magic method to retrieve if a variable is set in the viewpublic__set(string$key,mixed$value)Magic method to pass variables to the viewspublicstaticcleanTemplateAfter()Resets any template before layoutspublicstaticcleanTemplateBefore()Resets any "template before" layoutspublicstaticdisable()Disables the auto-rendering processpublicstaticdisableLevel( mixed$level )Disables a specific level of renderingpublicstaticenable()Enables the auto-rendering processpublicboolexists( string$view )Checks whether view existspublicstaticfinish()Finishes the render process by stopping the output bufferingpublicstringgetActionName()Gets the name of the action renderedpublicstring|arraygetActiveRenderPath()Returns the path (or paths) of the views that are currently renderedpublicstringgetBasePath()Gets base pathpublicstringgetControllerName()Gets the name of the controller renderedpublicintgetCurrentRenderLevel()publicManagerInterface|nullgetEventsManager()Returns the internal event managerpublicstring|nullgetLayout()Returns the name of the main viewpublicstringgetLayoutsDir()Gets the current layouts sub-directorypublicstringgetMainView()Returns the name of the main viewpublicstringgetPartial(string$partialPath,mixed$params = null)Renders a partial viewpublicstringgetPartialsDir()Gets the current partials sub-directorypublicstringgetRender(string$controllerName,string$actionName,array$params = [],mixed$configCallback = null)Perform the automatic rendering returning the output as a stringpublicintgetRenderLevel()publicstring|arraygetViewsDir()Gets views directorypublicboolhas( string$view )Checks whether view existspublicboolisDisabled()Whether automatic rendering is enabledpublicpartial(string$partialPath,mixed$params = null)Renders a partial viewpublicstaticpick( mixed$renderView )Choose a different view to render instead of last-controller/last-actionpublicboolprocessRender(string$controllerName,string$actionName,array$params = [],bool$fireEvents = true)Processes the view and templates; Fires events if neededpublicstaticregisterEngines( array$engines )Register templating enginespublicstatic|falserender(string$controllerName,string$actionName,array$params = [])Executes render process from dispatching datapublicstaticreset()Resets the view component to its factory default valuespublicstaticsetBasePath( string$basePath )Sets base path. Depending of your platform, always add a trailing slashpublicvoidsetEventsManager( ManagerInterface$eventsManager )Sets the events managerpublicstaticsetLayout( string$layout )Change the layout to be used instead of using the name of the latestpublicstaticsetLayoutsDir( string$layoutsDir )Sets the layouts sub-directory. Must be a directory under the viewspublicstaticsetMainView( string$viewPath )Sets default view name. Must be a file without extension in the viewspublicstaticsetParamToView(string$key,mixed$value)Adds parameters to views (alias of setVar)publicstaticsetPartialsDir( string$partialsDir )Sets a partials sub-directory. Must be a directory under the viewspublicstaticsetRenderLevel( int$level )Sets the render level for the viewpublicstaticsetTemplateAfter( mixed$templateAfter )Sets a "template after" controller layoutpublicstaticsetTemplateBefore( mixed$templateBefore )Sets a template before the controller layoutpublicstaticsetVars(array$params,bool$merge = true)Set all the render paramspublicstaticsetViewsDir( mixed$viewsDir )Sets the views directory. Depending of your platform,publicstaticstart()Starts rendering process enabling the output bufferingpublicstringtoString(string$controllerName,string$actionName,array$params = [])Renders the view and returns it as a stringprotectedengineRender(array$engines,string$viewPath,bool$silence,bool$mustClean = true)Checks whether view exists on registered extensions and render itprotectedarraygetViewsDirs()Gets views directoriesprotectedisAbsolutePath( string$path )Checks if a path is absolute or notprotectedarrayloadTemplateEngines()Loads registered template engines, if none is registered it will use

Constants

intLEVEL_ACTION_VIEW = 1Render Level: To the action view
intLEVEL_AFTER_TEMPLATE = 4Render Level: Render to the templates "after"
intLEVEL_BEFORE_TEMPLATE = 2Render Level: To the templates "before"
intLEVEL_LAYOUT = 3Render Level: To the controller layout
intLEVEL_MAIN_LAYOUT = 5Render Level: To the main layout
intLEVEL_NO_RENDER = 0Render Level: No render any view

Properties

protectedstring$actionName
protectedarray$activeRenderPaths
protectedstring$basePath = ""
protectedstring$controllerName
protectedint$currentRenderLevel = 0
protectedbool$disabled = false
protectedarray$disabledLevels = []
protectedarray|bool$engines = false
protectedManagerInterface|null$eventsManager
protectedstring|null$layout = null
protectedstring$layoutsDir = ""
protectedstring$mainView = "index"
protectedarray$options = []
protectedarray$params = []
protectedstring$partialsDir = ""
protectedarray|null$pickView
protectedint$renderLevel = 5
protectedarray$templatesAfter = []
protectedarray$templatesBefore = []
protectedarray$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

InterfaceSource 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

InterfaceSource on GitHub

Interface for Phalcon\Mvc\View

Method Summary

publiccleanTemplateAfter()Resets any template before layoutspubliccleanTemplateBefore()Resets any template before layoutspublicdisable()Disables the auto-rendering processpublicenable()Enables the auto-rendering processpublicfinish()Finishes the render process by stopping the output bufferingpublicstringgetActionName()Gets the name of the action renderedpublicstring|arraygetActiveRenderPath()Returns the path of the view that is currently renderedpublicstringgetBasePath()Gets base pathpublicstringgetControllerName()Gets the name of the controller renderedpublicstring|nullgetLayout()Returns the name of the main viewpublicstringgetLayoutsDir()Gets the current layouts sub-directorypublicstringgetMainView()Returns the name of the main viewpublicstringgetPartialsDir()Gets the current partials sub-directorypublicboolisDisabled()Whether the automatic rendering is disabledpublicpick( string$renderView )Choose a view different to render than last-controller/last-actionpublicregisterEngines( array$engines )Register templating enginespublicViewInterface|boolrender(string$controllerName,string$actionName,array$params = [])Executes render process from dispatching datapublicreset()Resets the view component to its factory default valuespublicsetBasePath( string$basePath )Sets base path. Depending of your platform, always add a trailing slashpublicsetLayout( string$layout )Change the layout to be used instead of using the name of the latestpublicsetLayoutsDir( string$layoutsDir )Sets the layouts sub-directory. Must be a directory under the viewspublicsetMainView( string$viewPath )Sets default view name. Must be a file without extension in the viewspublicsetPartialsDir( string$partialsDir )Sets a partials sub-directory. Must be a directory under the viewspublicViewInterfacesetRenderLevel( int$level )Sets the render level for the viewpublicsetTemplateAfter( mixed$templateAfter )Appends template after controller layoutpublicsetTemplateBefore( mixed$templateBefore )Appends template before controller layoutpublicstart()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

AbstractSource 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

protectedManagerInterface|null$eventsManager = null
protectedViewBaseInterface$view

Methods

Public · 6

__construct()

public function __construct(
    ViewBaseInterface $view,
    DiInterface|null $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

InterfaceSource 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

ClassSource 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

ClassSource 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

protectedCompiler$compiler
protectedManagerInterface|null$eventsManager
protectedarray$macros = []
protectedarray$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

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

Method Summary

public__construct( ViewBaseInterface|null$view = null )Phalcon\Mvc\View\Engine\Volt\CompilerpublicstaticaddExtension( mixed$extension )Registers a Volt's extensionpublicstaticaddFilter(string$name,mixed$definition)Register a new filter in the compilerpublicstaticaddFunction(string$name,mixed$definition)Register a new function in the compilerpublicstringattributeReader( array$expr )Resolves attribute readingpubliccompile(string$templatePath,bool$extendsMode = false)Compiles a template into a file applying the compiler optionspublicstringcompileAutoEscape(array$statement,bool$extendsMode)Compiles a "autoescape" statement returning PHP codepublicstringcompileCall(array$statement,bool$extendsMode)Compiles calls to macrospublicstringcompileCase(array$statement,bool$caseClause = true)Compiles a "case"/"default" clause returning PHP codepublicstringcompileDo( array$statement )Compiles a "do" statement returning PHP codepublicstringcompileEcho( array$statement )Compiles a {{ }} statement returning PHP codepublicstringcompileElseIf( array$statement )Compiles a "elseif" statement returning PHP codepubliccompileFile(string$path,string$compiledPath,bool$extendsMode = false)Compiles a template into a file forcing the destination pathpublicstringcompileForElse()Generates a 'forelse' PHP codepublicstringcompileForeach(array$statement,bool$extendsMode = false)Compiles a "foreach" intermediate code representation into plain PHP codepublicstringcompileIf(array$statement,bool$extendsMode = false)Compiles a 'if' statement returning PHP codepublicstringcompileInclude( array$statement )Compiles a 'include' statement returning PHP codepublicstringcompileMacro(array$statement,bool$extendsMode)Compiles macrospublicstringcompileReturn( array$statement )Compiles a "return" statement returning PHP codepublicstringcompileSet( array$statement )Compiles a "set" statement returning PHP code. The method accepts anpublicstringcompileString(string$viewCode,bool$extendsMode = false)Compiles a template into a stringpublicstringcompileSwitch(array$statement,bool$extendsMode = false)Compiles a 'switch' statement returning PHP codepublicstringexpression(array$expr,bool$doubleQuotes = false)Resolves an expression node in an AST volt treepublicfireExtensionEvent(string$name,array$arguments = [])Fires an event to registered extensionspublicstringfunctionCall(array$expr,bool$doubleQuotes = false)Resolves function intermediate code into PHP function callspublicstringgetCompiledTemplatePath()Returns the path to the last compiled templatepublicDiInterfacegetDI()Returns the internal dependency injectorpublicarraygetExtensions()Returns the list of extensions registered in VoltpublicarraygetFilters()Register the user registered filterspublicarraygetFunctions()Register the user registered functionspublicstring|nullgetOption( string$option )Returns a compiler's optionpublicarraygetOptions()Returns the compiler optionspublicstringgetTemplatePath()Returns the path that is currently being compiledpublicstringgetUniquePrefix()Return a unique prefix to be used as prefix for compiled variables andpublicarrayparse( string$viewCode )Parses a Volt template returning its intermediate representationpublicstringresolveTest(array$test,string$left)Resolves filter intermediate code into a valid PHP expressionpublicvoidsetDI( DiInterface$container )Sets the dependency injectorpublicstaticsetOption(string$option,mixed$value)Sets a single compiler optionpublicstaticsetOptions( array$options )Sets the compiler optionspublicstaticsetUniquePrefix( string$prefix )Set a unique prefix to be used as prefix for compiled variablesprotectedarray|stringcompileSource(string$viewCode,bool$extendsMode = false)Compiles a Volt source code returning a PHP plain versionprotectedgetFinalPath( string$path )Gets the final path with VIEWprotectedstringresolveFilter(array$filter,string$left)Resolves filter intermediate code into PHP function callsprotectedstringstatementList(array$statements,bool$extendsMode = false)Traverses a statement list compiling each of its nodesprotectedstatementListOrExtends( mixed$statements )Compiles a block of statements

Properties

protectedbool$autoescape = false
protectedint$blockLevel = 0
protectedarray|null$blocksTODO: Make array only?
protectedstring|null$compiledTemplatePath
protectedDiInterface|null$container = null
protectedstring|null$currentBlock = null
protectedstring|null$currentPath = null
protectedint$exprLevel = 0
protectedbool$extended = false
protectedarray|bool$extendedBlocksTODO: Make it always array
protectedarray$extensions = []
protectedarray$filters = []
protectedarray$forElsePointers = []
protectedint$foreachLevel = 0
protectedarray$functions = []
protectedint$level = 0
protectedarray$loopPointers = []
protectedarray$macros = []
protectedarray$options = []
protectedstring$prefix = ""
protectedViewBaseInterface|null$view

Methods

Public · 40

__construct()

public function __construct( ViewBaseInterface|null $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

ClassSource on GitHub

Class for exceptions thrown by Phalcon\Mvc\View

Uses Phalcon\Mvc\View\Exception

Method Summary

Properties

protectedarray$statement = []

Methods

Public · 2

__construct()

public function __construct(
    string $message = "",
    array $statement = [],
    int $code = 0,
    \Exception|null $previous = null
);

getStatement()

public function getStatement(): array;

Gets currently parsed statement (if any).

Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidExtension

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidHaystack

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidOptionType

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidPathType

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\InvalidStatement

ClassSource 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

ClassSource 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

ClassSource 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

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression

ClassSource 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

ClassSource 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

ClassSource 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

ClassSource 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

ClassSource on GitHub

Uses Phalcon\Mvc\View\Engine\Volt\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exception

ClassSource on GitHub

Phalcon\Mvc\View\Exception

Class for exceptions thrown by Phalcon\Mvc\View

Mvc\View\Exceptions\InvalidEngineRegistration

ClassSource on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $extension );

Mvc\View\Exceptions\InvalidViewsDirType

ClassSource on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exceptions\SimpleViewNotFound

ClassSource on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $viewsDirPath );

Mvc\View\Exceptions\SimpleViewServicesUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exceptions\ViewNotFound

ClassSource on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct( string $viewPath );

Mvc\View\Exceptions\ViewServicesUnavailable

ClassSource on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Exceptions\ViewsDirItemMustBeString

ClassSource on GitHub

Uses Phalcon\Mvc\View\Exception

Method Summary

Methods

Public · 1

__construct()

public function __construct();

Mvc\View\Simple

ClassSource 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\Contracts\View\Renderer · 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

protectedstring$activeRenderPath
protectedEngineInterface[]|false$engines = false
protectedManagerInterface|null$eventsManager
protectedarray$options = []
protectedstring$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

Mvc\View\Traits\ViewParamsTrait

TraitSource on GitHub

Shared view parameter and content accessors

@todo v7 - inspect the View/Simple interfaces (ViewInterface vs ViewBaseInterface) to see whether these accessors can be unified behind a shared contract

  • Phalcon\Mvc\View\Traits\ViewParamsTrait

Used by Phalcon\Mvc\View · Phalcon\Mvc\View\Simple

Method Summary

Properties

protectedstring$content = ""
protectedarray$registeredEngines = null@todo Use a default [] once Zephir supports array trait defaults
protectedarray$viewParams = null@todo Use a default [] once Zephir supports array trait defaults

Methods

Public · 6

getContent()

public function getContent(): string;

Returns output from another view stage

getParamsToView()

public function getParamsToView(): array;

Returns parameters to views

getRegisteredEngines()

public function getRegisteredEngines(): array;

getVar()

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

Returns a parameter previously set in the view

setContent()

public function setContent( string $content ): static;

Externally sets the view content

$this->view->setContent("<h1>hello</h1>");

setVar()

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

Set a single view parameter

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

Type to search…

↑↓ navigate↵ selectEsc close