Phalcon mvc
NOTE
All classes are prefixed with Phalcon
Mvc\Application¶
Class Source on GitHub
Phalcon\Mvc\Application
This component encapsulates all the complex operations behind instantiating every component needed and integrating it with the rest to allow the MVC pattern to operate as desired.
use Phalcon\Mvc\Application;
class MyApp extends Application
{
/**
* Register the services here to make them general or register
* in the ModuleDefinition to make them module-specific
*\/
protected function registerServices()
{
}
/**
* This method registers all the modules in the application
*\/
public function main()
{
$this->registerModules(
[
"frontend" => [
"className" => "Multiple\\Frontend\\Module",
"path" => "../apps/frontend/Module.php",
],
"backend" => [
"className" => "Multiple\\Backend\\Module",
"path" => "../apps/backend/Module.php",
],
]
);
}
}
$application = new MyApp();
$application->main();
stdClassPhalcon\Di\InjectablePhalcon\Application\AbstractApplicationPhalcon\Mvc\Application
Uses Closure · Phalcon\Application\AbstractApplication · Phalcon\Di\DiInterface · Phalcon\Events\ManagerInterface · Phalcon\Http\ResponseInterface · Phalcon\Mvc\Application\Exception · Phalcon\Mvc\Application\Exceptions\ContainerRequired · Phalcon\Mvc\Application\Exceptions\InvalidModuleDefinition · Phalcon\Mvc\Application\Exceptions\ModuleDefinitionPathNotFound · Phalcon\Mvc\ModuleDefinitionInterface · Phalcon\Mvc\Router\RouteInterface
Method Summary¶
public ResponseInterface|bool handle( string $uri ) Handles a MVC request public static sendCookiesOnHandleRequest( bool $sendCookies ) Enables or disables sending cookies by each request handling public static sendHeadersOnHandleRequest( bool $sendHeaders ) Enables or disables sending headers by each request handling public static useImplicitView( bool $implicitView ) By default. The view is implicitly buffering all the output Properties¶
protected bool $implicitView = true protected bool $sendCookies = true protected bool $sendHeaders = true Methods¶
handle()¶
Handles a MVC request
sendCookiesOnHandleRequest()¶
Enables or disables sending cookies by each request handling
sendHeadersOnHandleRequest()¶
Enables or disables sending headers by each request handling
useImplicitView()¶
By default. The view is implicitly buffering all the output You can full disable the view component using this method
Mvc\Application\Exception¶
Class Source on GitHub
Phalcon\Mvc\Application\Exception
Exceptions thrown in Phalcon\Mvc\Application class will use this class
Mvc\Application\Exceptions\ContainerRequired¶
Class Source on GitHub
\ExceptionPhalcon\Application\ExceptionPhalcon\Mvc\Application\ExceptionPhalcon\Mvc\Application\Exceptions\ContainerRequired
Uses Phalcon\Mvc\Application\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Application\Exceptions\InvalidModuleDefinition¶
Class Source on GitHub
\ExceptionPhalcon\Application\ExceptionPhalcon\Mvc\Application\ExceptionPhalcon\Mvc\Application\Exceptions\InvalidModuleDefinition
Uses Phalcon\Mvc\Application\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Application\Exceptions\ModuleDefinitionPathNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Application\ExceptionPhalcon\Mvc\Application\ExceptionPhalcon\Mvc\Application\Exceptions\ModuleDefinitionPathNotFound
Uses Phalcon\Mvc\Application\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Controller¶
Abstract Source on GitHub
Phalcon\Mvc\Controller
Every application controller should extend this class that encapsulates all the controller functionality
The controllers provide the “flow” between models and views. Controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
<?php
class PeopleController extends \Phalcon\Mvc\Controller
{
// This action will be executed by default
public function indexAction()
{
}
public function findAction()
{
}
public function saveAction()
{
// Forwards flow to the index action
return $this->dispatcher->forward(
[
"controller" => "people",
"action" => "index",
]
);
}
}
stdClassPhalcon\Di\InjectablePhalcon\Mvc\Controller— implementsPhalcon\Mvc\ControllerInterface,Phalcon\Events\EventsAwareInterface
Uses Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface
Method Summary¶
public __construct() Phalcon\Mvc\Controller constructor public ManagerInterface|null getEventsManager() Returns the internal event manager public void setEventsManager( ManagerInterface $eventsManager ) Sets the events manager protected mixed|bool fireManagerEvent(string $eventName,mixed $data = null,bool $cancellable = true) Helper method to fire an event Methods¶
__construct()¶
Phalcon\Mvc\Controller constructor
getEventsManager()¶
Returns the internal event manager
setEventsManager()¶
Sets the events manager
fireManagerEvent()¶
protected function fireManagerEvent(
string $eventName,
mixed $data = null,
bool $cancellable = true
): mixed|bool;
Helper method to fire an event
Mvc\ControllerInterface¶
Interface Source on GitHub
Phalcon\Mvc\ControllerInterface
Interface for controller handlers
Phalcon\Mvc\ControllerInterface
Mvc\Controller\BindModelInterface¶
Interface Source on GitHub
Phalcon\Mvc\Controller\BindModelInterface
Interface for Phalcon\Mvc\Controller
Phalcon\Mvc\Controller\BindModelInterface
Method Summary¶
Methods¶
getModelName()¶
Return the model name associated with this controller
Mvc\Dispatcher¶
Class Source on GitHub
Dispatching is the process of taking the request object, extracting the module name, controller name, action name, and optional parameters contained in it, and then instantiating a controller and calling an action of that controller.
$di = new \Phalcon\Di\Di();
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$dispatcher->setDI($di);
$dispatcher->setControllerName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);
$controller = $dispatcher->dispatch();
stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Dispatcher\AbstractDispatcherPhalcon\Mvc\Dispatcher— implementsPhalcon\Mvc\DispatcherInterface
Uses Phalcon\Dispatcher\AbstractDispatcher · Phalcon\Events\ManagerInterface · Phalcon\Http\ResponseInterface · Phalcon\Mvc\Dispatcher\Exception · Phalcon\Mvc\Dispatcher\Exceptions\ResponseServiceUnavailable
Method Summary¶
public void forward( array $forward ) Forwards the execution flow to another controller/action. public ControllerInterface getActiveController() Returns the active controller in the dispatcher public string getControllerClass() Possible controller class name that will be located to dispatch the public string getControllerName() Gets last dispatched controller name public ControllerInterface getLastController() Returns the latest dispatched controller public string getPreviousControllerName() Gets previous dispatched controller name public DispatcherInterface setControllerName( string $controllerName ) Sets the controller name to be dispatched public DispatcherInterface setControllerSuffix( string $controllerSuffix ) Sets the default controller suffix public DispatcherInterface setDefaultController( string $controllerName ) Sets the default controller name protected handleException( \Exception $exception ) Handles a user exception protected throwDispatchException(string $message,int $exceptionCode = 0) Throws an internal exception Properties¶
protected string $defaultAction = "index" protected string $defaultHandler = "index" protected string $handlerSuffix = "Controller" Methods¶
forward()¶
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()¶
Returns the active controller in the dispatcher
getControllerClass()¶
Possible controller class name that will be located to dispatch the request
getControllerName()¶
Gets last dispatched controller name
getLastController()¶
Returns the latest dispatched controller
getPreviousControllerName()¶
Gets previous dispatched controller name
Note: This is an Mvc-specific alias for the base getPreviousHandlerName().
setControllerName()¶
Sets the controller name to be dispatched
setControllerSuffix()¶
Sets the default controller suffix
setDefaultController()¶
Sets the default controller name
handleException()¶
Handles a user exception
throwDispatchException()¶
Throws an internal exception
Mvc\DispatcherInterface¶
Interface Source on GitHub
Phalcon\Mvc\DispatcherInterface
Interface for Phalcon\Mvc\Dispatcher
Phalcon\Contracts\Dispatcher\DispatcherPhalcon\Contracts\Mvc\DispatcherPhalcon\Mvc\DispatcherInterface
Uses Phalcon\Contracts\Mvc\Dispatcher
Mvc\Dispatcher\Exception¶
Class Source on GitHub
Phalcon\Mvc\Dispatcher\Exception
Exceptions thrown in Phalcon\Mvc\Dispatcher will use this class
\ExceptionPhalcon\Dispatcher\ExceptionPhalcon\Mvc\Dispatcher\Exception
Mvc\Dispatcher\Exceptions\ResponseServiceUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Dispatcher\ExceptionPhalcon\Mvc\Dispatcher\ExceptionPhalcon\Mvc\Dispatcher\Exceptions\ResponseServiceUnavailable
Uses Phalcon\Mvc\Dispatcher\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\EntityInterface¶
Interface Source on GitHub
Phalcon\Mvc\EntityInterface
Interface for Phalcon\Mvc\Collection and Phalcon\Mvc\Model
Phalcon\Mvc\EntityInterface
Method Summary¶
public mixed|null readAttribute( string $attribute ) Reads an attribute value by its name public writeAttribute(string $attribute,mixed $value) Writes an attribute value by its name Methods¶
readAttribute()¶
Reads an attribute value by its name
writeAttribute()¶
Writes an attribute value by its name
Mvc\Micro¶
Class Source on GitHub
Phalcon\Mvc\Micro
With Phalcon you can create "Micro-Framework like" applications. By doing this, you only need to write a minimal amount of code to create a PHP application. Micro applications are suitable to small applications, APIs and prototypes in a practical way.
$app = new \Phalcon\Mvc\Micro();
$app->get(
"/say/welcome/{name}",
function ($name) {
echo "<h1>Welcome $name!</h1>";
}
);
$app->handle("/say/welcome/Phalcon");
stdClassPhalcon\Di\InjectablePhalcon\Mvc\Micro— implementsArrayAccess,Phalcon\Events\EventsAwareInterface
Uses ArrayAccess · Closure · Phalcon\Cache\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Di\FactoryDefault · Phalcon\Di\Injectable · Phalcon\Di\ServiceInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Http\ResponseInterface · Phalcon\Mvc\Micro\Collection · Phalcon\Mvc\Micro\CollectionInterface · Phalcon\Mvc\Micro\Exception · Phalcon\Mvc\Micro\Exceptions\ContainerRequired · Phalcon\Mvc\Micro\Exceptions\ErrorHandlerNotCallable · Phalcon\Mvc\Micro\Exceptions\HandlerNotCallable · Phalcon\Mvc\Micro\Exceptions\InvalidRegisteredHandler · Phalcon\Mvc\Micro\Exceptions\MissingCollectionMainHandler · Phalcon\Mvc\Micro\Exceptions\NoHandlersToMount · Phalcon\Mvc\Micro\Exceptions\NoMatchedRouteHandler · Phalcon\Mvc\Micro\Exceptions\NotFoundHandlerNotCallable · Phalcon\Mvc\Micro\Exceptions\ResponseHandlerNotCallable · Phalcon\Mvc\Micro\LazyLoader · Phalcon\Mvc\Micro\MiddlewareInterface · Phalcon\Mvc\Model\BinderInterface · Phalcon\Mvc\Router\RouteInterface · Throwable
Method Summary¶
public __construct( DiInterface $container = null ) Phalcon\Mvc\Micro constructor public static after( mixed $handler ) Appends an 'after' middleware to be called after execute the route public static afterBinding( mixed $handler ) Appends a afterBinding middleware to be called after model binding public static before( mixed $handler ) Appends a before middleware to be called before execute the route public RouteInterface delete(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is DELETE public static error( mixed $handler ) Sets a handler that will be called when an exception is thrown handling public static finish( mixed $handler ) Appends a 'finish' middleware to be called when the request is finished public RouteInterface get(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is GET public getActiveHandler() Return the handler that will be called for the matched route public array getBoundModels() Returns bound models from binder instance public ManagerInterface|null getEventsManager() Returns the internal event manager public array getHandlers() Returns the internal handlers attached to the application public BinderInterface|null getModelBinder() Gets model binder public getReturnedValue() Returns the value returned by the executed handler public RouterInterface getRouter() Returns the internal router used by the application public getService( string $serviceName ) Obtains a service from the DI public getSharedService( string $serviceName ) Obtains a shared service from the DI public handle( string $uri ) Handle the whole request public bool hasService( string $serviceName ) Checks if a service is registered in the DI public RouteInterface head(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is HEAD public RouteInterface map(string $routePattern,mixed $handler) Maps a route to a handler without any HTTP method constraint public static mount( CollectionInterface $collection ) Mounts a collection of handlers public static notFound( mixed $handler ) Sets a handler that will be called when the router does not match any of public bool offsetExists( mixed $offset ) Check if a service is registered in the internal services container using public mixed offsetGet( mixed $offset ) Allows to obtain a shared service in the internal services container public void offsetSet(mixed $offset,mixed $value) Allows to register a shared service in the internal services container public void offsetUnset( mixed $offset ) Removes a service from the internal services container using the array public RouteInterface options(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is OPTIONS public RouteInterface patch(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is PATCH public RouteInterface post(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is POST public RouteInterface put(string $routePattern,mixed $handler) Maps a route to a handler that only matches if the HTTP method is PUT public self setActiveHandler( mixed $activeHandler ) Sets externally the handler that must be called by the matched route public void setDI( DiInterface $container ) Sets the DependencyInjector container public void setEventsManager( ManagerInterface $eventsManager ) Sets the events manager public static setModelBinder(BinderInterface $modelBinder,mixed $cache = null) Sets model binder public static setResponseHandler( mixed $handler ) Appends a custom 'response' handler to be called instead of the default public ServiceInterface setService(string $serviceName,mixed $definition,bool $isShared = false) Sets a service from the DI public void stop() Stops the middleware execution avoiding than other middlewares be Properties¶
protected callable|null $activeHandler = null protected array $afterBindingHandlers = [] protected array $afterHandlers = [] protected array $beforeHandlers = [] protected DiInterface|null $container = null protected callable|null $errorHandler = null protected ManagerInterface|null $eventsManager = null protected array $finishHandlers = [] protected array $handlers = [] protected BinderInterface|null $modelBinder = null protected callable|null $notFoundHandler = null protected callable|null $responseHandler = null protected mixed|null $returnedValue = null protected RouterInterface|null $router = null protected bool $stopped = false Methods¶
__construct()¶
Phalcon\Mvc\Micro constructor
after()¶
Appends an 'after' middleware to be called after execute the route
afterBinding()¶
Appends a afterBinding middleware to be called after model binding
before()¶
Appends a before middleware to be called before execute the route
delete()¶
Maps a route to a handler that only matches if the HTTP method is DELETE
error()¶
Sets a handler that will be called when an exception is thrown handling the route
finish()¶
Appends a 'finish' middleware to be called when the request is finished
get()¶
Maps a route to a handler that only matches if the HTTP method is GET
getActiveHandler()¶
Return the handler that will be called for the matched route
getBoundModels()¶
Returns bound models from binder instance
getEventsManager()¶
Returns the internal event manager
getHandlers()¶
Returns the internal handlers attached to the application
getModelBinder()¶
Gets model binder
getReturnedValue()¶
Returns the value returned by the executed handler
getRouter()¶
Returns the internal router used by the application
getService()¶
Obtains a service from the DI
getSharedService()¶
Obtains a shared service from the DI
handle()¶
Handle the whole request
hasService()¶
Checks if a service is registered in the DI
head()¶
Maps a route to a handler that only matches if the HTTP method is HEAD
map()¶
Maps a route to a handler without any HTTP method constraint
mount()¶
Mounts a collection of handlers
notFound()¶
Sets a handler that will be called when the router does not match any of the defined routes
offsetExists()¶
Check if a service is registered in the internal services container using the array syntax
offsetGet()¶
Allows to obtain a shared service in the internal services container using the array syntax
offsetSet()¶
Allows to register a shared service in the internal services container using the array syntax
offsetUnset()¶
Removes a service from the internal services container using the array syntax
options()¶
Maps a route to a handler that only matches if the HTTP method is OPTIONS
patch()¶
Maps a route to a handler that only matches if the HTTP method is PATCH
post()¶
Maps a route to a handler that only matches if the HTTP method is POST
put()¶
Maps a route to a handler that only matches if the HTTP method is PUT
setActiveHandler()¶
Sets externally the handler that must be called by the matched route
setDI()¶
Sets the DependencyInjector container
setEventsManager()¶
Sets the events manager
setModelBinder()¶
Sets model binder
setResponseHandler()¶
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()¶
Stops the middleware execution avoiding than other middlewares be executed
Mvc\Micro\Collection¶
Class Source on GitHub
Phalcon\Mvc\Micro\Collection
Groups Micro-Mvc handlers as controllers
$app = new \Phalcon\Mvc\Micro();
$collection = new Collection();
$collection->setHandler(
new PostsController()
);
$collection->get("/posts/edit/{id}", "edit");
$app->mount($collection);
Phalcon\Mvc\Micro\Collection— implementsPhalcon\Mvc\Micro\CollectionInterface
Method Summary¶
public CollectionInterface delete(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is DELETE. public CollectionInterface get(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is GET. public mixed getHandler() Returns the main handler public array getHandlers() Returns the registered handlers public string getPrefix() Returns the collection prefix if any public CollectionInterface head(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is HEAD. public bool isLazy() Returns if the main handler must be lazy loaded public CollectionInterface map(string $routePattern,callable $handler,string $name = null) Maps a route to a handler. public CollectionInterface mapVia(string $routePattern,callable $handler,mixed $method,string $name = null) Maps a route to a handler via methods. public CollectionInterface options(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is public CollectionInterface patch(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PATCH. public CollectionInterface post(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is POST. public CollectionInterface put(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PUT. public CollectionInterface setHandler(mixed $handler,bool $isLazy = false) Sets the main handler. public CollectionInterface setLazy( bool $isLazy ) Sets if the main handler must be lazy loaded public CollectionInterface setPrefix( string $prefix ) Sets a prefix for all routes added to the collection protected void addMap(mixed $method,string $routePattern,callable $handler,string $name = null) Internal function to add a handler to the group. Properties¶
protected callable $handler protected array $handlers = [] protected bool $isLazy = false protected string $prefix = "" Methods¶
delete()¶
public function delete(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is DELETE.
get()¶
public function get(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is GET.
getHandler()¶
Returns the main handler
getHandlers()¶
Returns the registered handlers
getPrefix()¶
Returns the collection prefix if any
head()¶
public function head(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is HEAD.
isLazy()¶
Returns if the main handler must be lazy loaded
map()¶
public function map(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler.
mapVia()¶
public function mapVia(
string $routePattern,
callable $handler,
mixed $method,
string $name = null
): CollectionInterface;
Maps a route to a handler via methods.
options()¶
public function options(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is OPTIONS.
patch()¶
public function patch(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is PATCH.
post()¶
public function post(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is POST.
put()¶
public function put(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is PUT.
setHandler()¶
Sets the main handler.
setLazy()¶
Sets if the main handler must be lazy loaded
setPrefix()¶
Sets a prefix for all routes added to the collection
addMap()¶
protected function addMap(
mixed $method,
string $routePattern,
callable $handler,
string $name = null
): void;
Internal function to add a handler to the group.
Mvc\Micro\CollectionInterface¶
Interface Source on GitHub
Phalcon\Mvc\Micro\CollectionInterface
Interface for Phalcon\Mvc\Micro\Collection
Phalcon\Mvc\Micro\CollectionInterface
Method Summary¶
public CollectionInterface delete(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is DELETE public CollectionInterface get(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is GET public mixed getHandler() Returns the main handler public array getHandlers() Returns the registered handlers public string getPrefix() Returns the collection prefix if any public CollectionInterface head(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is HEAD public bool isLazy() Returns if the main handler must be lazy loaded public CollectionInterface map(string $routePattern,callable $handler,string $name = null) Maps a route to a handler public CollectionInterface options(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is OPTIONS public CollectionInterface patch(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PATCH public CollectionInterface post(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is POST public CollectionInterface put(string $routePattern,callable $handler,string $name = null) Maps a route to a handler that only matches if the HTTP method is PUT public CollectionInterface setHandler(mixed $handler,bool $isLazy = false) Sets the main handler public CollectionInterface setLazy( bool $isLazy ) Sets if the main handler must be lazy loaded public CollectionInterface setPrefix( string $prefix ) Sets a prefix for all routes added to the collection Methods¶
delete()¶
public function delete(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is DELETE
get()¶
public function get(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is GET
getHandler()¶
Returns the main handler
getHandlers()¶
Returns the registered handlers
getPrefix()¶
Returns the collection prefix if any
head()¶
public function head(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is HEAD
isLazy()¶
Returns if the main handler must be lazy loaded
map()¶
public function map(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler
options()¶
public function options(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is OPTIONS
patch()¶
public function patch(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is PATCH
post()¶
public function post(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is POST
put()¶
public function put(
string $routePattern,
callable $handler,
string $name = null
): CollectionInterface;
Maps a route to a handler that only matches if the HTTP method is PUT
setHandler()¶
Sets the main handler
setLazy()¶
Sets if the main handler must be lazy loaded
setPrefix()¶
Sets a prefix for all routes added to the collection
Mvc\Micro\Exception¶
Class Source on GitHub
Exceptions thrown in Phalcon\Mvc\Micro will use this class
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\ContainerRequiredPhalcon\Mvc\Micro\Exceptions\ErrorHandlerNotCallablePhalcon\Mvc\Micro\Exceptions\HandlerNotCallablePhalcon\Mvc\Micro\Exceptions\InvalidRegisteredHandlerPhalcon\Mvc\Micro\Exceptions\LazyHandlerNotFoundPhalcon\Mvc\Micro\Exceptions\MissingCollectionMainHandlerPhalcon\Mvc\Micro\Exceptions\NoHandlersToMountPhalcon\Mvc\Micro\Exceptions\NoMatchedRouteHandlerPhalcon\Mvc\Micro\Exceptions\NotFoundHandlerNotCallablePhalcon\Mvc\Micro\Exceptions\ResponseHandlerNotCallable
Mvc\Micro\Exceptions\ContainerRequired¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\ContainerRequired
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\ErrorHandlerNotCallable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\ErrorHandlerNotCallable
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\HandlerNotCallable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\HandlerNotCallable
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\InvalidRegisteredHandler¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\InvalidRegisteredHandler
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\LazyHandlerNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\LazyHandlerNotFound
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\MissingCollectionMainHandler¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\MissingCollectionMainHandler
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\NoHandlersToMount¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\NoHandlersToMount
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\NoMatchedRouteHandler¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\NoMatchedRouteHandler
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\NotFoundHandlerNotCallable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\NotFoundHandlerNotCallable
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\Exceptions\ResponseHandlerNotCallable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\Exceptions\ResponseHandlerNotCallable
Uses Phalcon\Mvc\Micro\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Micro\LazyLoader¶
Class Source on GitHub
Phalcon\Mvc\Micro\LazyLoader
Lazy-Load of handlers for Mvc\Micro using auto-loading
Phalcon\Mvc\Micro\LazyLoader
Uses Phalcon\Mvc\Micro\Exceptions\LazyHandlerNotFound · Phalcon\Mvc\Model\BinderInterface
Method Summary¶
public __construct( string $definition ) Phalcon\Mvc\Micro\LazyLoader constructor public callMethod(string $method,mixed $arguments,BinderInterface $modelBinder = null) Calling __call method public string getDefinition() public object|null getHandler() Properties¶
protected string $definition protected object|null $handler = null Methods¶
__construct()¶
Phalcon\Mvc\Micro\LazyLoader constructor
callMethod()¶
public function callMethod(
string $method,
mixed $arguments,
BinderInterface $modelBinder = null
);
Calling __call method
getDefinition()¶
getHandler()¶
Mvc\Micro\MiddlewareInterface¶
Interface Source on GitHub
Allows to implement Phalcon\Mvc\Micro middleware in classes
Phalcon\Mvc\Micro\MiddlewareInterface
Uses Phalcon\Mvc\Micro
Method Summary¶
Methods¶
call()¶
Calls the middleware
Mvc\Model¶
Abstract Source on GitHub
Phalcon\Mvc\Model
Phalcon\Mvc\Model connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It‘s an implementation of the object-relational mapping (ORM).
A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models.
Phalcon\Mvc\Model is the first ORM written in Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use.
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() === false) {
echo "Umh, We can store robots: ";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message;
}
} else {
echo "Great, a new robot was saved successfully!";
}
Magic property and method resolution:
__get($property) resolves in order: a relation alias (returning unsaved dirtyRelated records first, then a non-reusable single related model held in the related cache - resultsets and reusable relations are never served from that cache - otherwise the freshly fetched related records); then a get<Property>() getter when one exists; otherwise it raises an "undefined property" notice and returns null.
__call() / __callStatic($method, $arguments) resolve the findBy<Field>, findFirstBy<Field>, and countBy<Field> magic finders through invokeFinder(). The instance __call() additionally tries relation getters and a behavior/listener missingMethod() hook. An unresolved method throws Phalcon\Mvc\Model\Exceptions\MethodNotFound.
@template T of static
stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Mvc\Model— implementsPhalcon\Mvc\EntityInterface,Phalcon\Mvc\ModelInterface,Phalcon\Mvc\Model\ResultInterface,Serializable,JsonSerializable
Uses JsonSerializable · Phalcon\Db\Adapter\AdapterInterface · Phalcon\Db\Column · Phalcon\Db\Enum · Phalcon\Db\Geometry\WkbParser · Phalcon\Db\RawValue · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Events\ManagerInterface · Phalcon\Filter\Validation\ValidationInterface · Phalcon\Messages\Message · Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\BehaviorInterface · Phalcon\Mvc\Model\Criteria · Phalcon\Mvc\Model\CriteriaInterface · Phalcon\Mvc\Model\Exception · Phalcon\Mvc\Model\Exceptions\BelongsToRequiresObject · Phalcon\Mvc\Model\Exceptions\BindTypeNotDefined · Phalcon\Mvc\Model\Exceptions\CannotResolveAttribute · Phalcon\Mvc\Model\Exceptions\ColumnNotInMap · Phalcon\Mvc\Model\Exceptions\ColumnNotInTableColumns · Phalcon\Mvc\Model\Exceptions\ColumnNotInTableMap · Phalcon\Mvc\Model\Exceptions\DataTypeNotDefined · Phalcon\Mvc\Model\Exceptions\IdentityNotInColumnMap · Phalcon\Mvc\Model\Exceptions\IdentityNotInTableColumns · Phalcon\Mvc\Model\Exceptions\InvalidDumpResultKey · Phalcon\Mvc\Model\Exceptions\InvalidFindParameters · Phalcon\Mvc\Model\Exceptions\InvalidModelsManagerService · Phalcon\Mvc\Model\Exceptions\InvalidModelsMetadataService · Phalcon\Mvc\Model\Exceptions\MethodNotFound · Phalcon\Mvc\Model\Exceptions\ModelOrmServicesUnavailable · Phalcon\Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet · Phalcon\Mvc\Model\Exceptions\PrimaryKeyRequired · Phalcon\Mvc\Model\Exceptions\PropertyNotAccessible · Phalcon\Mvc\Model\Exceptions\RecordCannotRefresh · Phalcon\Mvc\Model\Exceptions\RecordNotPersisted · Phalcon\Mvc\Model\Exceptions\RelationNotDefined · Phalcon\Mvc\Model\Exceptions\RelationRequiresObjectOrArray · Phalcon\Mvc\Model\Exceptions\SnapshotsDisabled · Phalcon\Mvc\Model\Exceptions\StaticMethodRequiresOneArgument · Phalcon\Mvc\Model\Exceptions\UpdateSnapshotDisabled · Phalcon\Mvc\Model\ManagerInterface · Phalcon\Mvc\Model\MetaDataInterface · Phalcon\Mvc\Model\Query · Phalcon\Mvc\Model\QueryInterface · Phalcon\Mvc\Model\Query\Builder · Phalcon\Mvc\Model\Query\BuilderInterface · Phalcon\Mvc\Model\Relation · Phalcon\Mvc\Model\RelationInterface · Phalcon\Mvc\Model\ResultInterface · Phalcon\Mvc\Model\Resultset · Phalcon\Mvc\Model\ResultsetInterface · Phalcon\Mvc\Model\TransactionInterface · Phalcon\Mvc\Model\ValidationFailed · Phalcon\Support\Collection · Phalcon\Support\Collection\CollectionInterface · Phalcon\Support\Settings · Serializable
Method Summary¶
public __call(string $method,array $arguments) Handles method calls when a method is not implemented public __callStatic(string $method,array $arguments) Handles method calls when a static method is not implemented public __construct(mixed $data = null,DiInterface $container = null,ManagerInterface $modelsManager = null) Phalcon\Mvc\Model constructor public __get( string $property ) Magic method to get related records using the relation alias as a public bool __isset( string $property ) Magic method to check if a property is a valid relation public array __serialize() Serializes a model public __set(string $property,mixed $value) Magic method to assign values to the the model public void __unserialize( array $data ) Unserializes an array to the model public void addBehavior( BehaviorInterface $behavior ) Setups a behavior in a model public ModelInterface appendMessage( MessageInterface $message ) Appends a customized message on the validation process public void appendMessagesFrom( mixed $model ) ** public ModelInterface assign(array $data,mixed $whiteList = null,mixed $dataColumnMap = null) Assigns values to a model from an array public double|ResultsetInterface average( array $parameters = [] ) Returns the average value on a column for a result-set of rows matching public ModelInterface cloneResult(ModelInterface $base,array $data,int $dirtyState = 0) Assigns values to a model from an array returning a new model public ModelInterface cloneResultMap(mixed $base,array $data,mixed $columnMap,int $dirtyState = 0,bool $keepSnapshots = null) Assigns values to a model from an array, returning a new model. public cloneResultMapHydrate(array $data,mixed $columnMap,int $hydrationMode) Returns an hydrated result based on the data and the column map public int|ResultsetInterface count( mixed $parameters = null ) Counts how many records match the specified conditions. public bool create() Inserts a model instance. If the instance already exists in the public bool delete() Deletes a model instance. Returning true on success or false otherwise. public bool doSave( CollectionInterface $visited ) Inserted or updates model instance, expects a visited list of objects. public array dump() Returns a simple representation of the object that can be used with public ResultsetInterface find( mixed $parameters = null ) Query for a set of records that match the specified conditions public mixed|null findFirst( mixed $parameters = null ) Query the first record that matches the specified conditions public bool fireEvent( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public bool fireEventCancel( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public array getChangedFields() Returns a list of changed values. public int getDirtyState() Returns one of the DIRTY_STATE_* constants telling if the record exists public EventsManagerInterface|null getEventsManager() Returns the custom events manager or null if there is no custom events manager public MessageInterface[] getMessages( mixed $filter = null ) Returns array of validation messages public ManagerInterface getModelsManager() Returns the models manager related to the entity instance public MetaDataInterface getModelsMetaData() {@inheritdoc} public array getOldSnapshotData() Returns the internal old snapshot data public int getOperationMade() Returns the type of the latest operation performed by the ORM public AdapterInterface getReadConnection() Gets the connection used to read data for the model public string getReadConnectionService() Returns the DependencyInjection connection service name used to read data public getRelated(string $alias,mixed $arguments = null) Returns related records based on defined relations public string|null getSchema() Returns schema name where the mapped table is located public array getSnapshotData() Returns the internal snapshot data public string getSource() Returns the table name mapped in the model public TransactionInterface|null getTransaction() public array getUpdatedFields() Returns a list of updated values. public AdapterInterface getWriteConnection() Gets the connection used to write data to the model public string getWriteConnectionService() Returns the DependencyInjection connection service name used to write public bool hasChanged(mixed $fieldName = null,bool $allFields = false) Check if a specific attribute has changed public bool hasSnapshotData() Checks if the object has internal snapshot data public bool hasUpdated(mixed $fieldName = null,bool $allFields = false) Check if a specific attribute was updated public bool isRelationshipLoaded( string $relationshipAlias ) Checks if saved related records have already been loaded. public array jsonSerialize() Serializes the object for json_encode public mixed maximum( mixed $parameters = null ) Returns the maximum value of a column for a result-set of rows that match public mixed minimum( mixed $parameters = null ) Returns the minimum value of a column for a result-set of rows that match public CriteriaInterface query( DiInterface $container = null ) Create a criteria for a specific model public mixed|null readAttribute( string $attribute ) Reads an attribute value by its name public ModelInterface refresh() Refreshes the model attributes re-querying the record from the database public bool save() Inserts or updates a model instance. Returning true on success or false public string|null serialize() Serializes the object ignoring connections, services, related objects or public void setConnectionService( string $connectionService ) Sets the DependencyInjection connection service name public ModelInterface|bool setDirtyState( int $dirtyState ) Sets the dirty state of the object using one of the DIRTY_STATE_* constants public setEventsManager( EventsManagerInterface $eventsManager ) Sets a custom events manager public setOldSnapshotData(array $data,mixed $columnMap = null) Sets the record's old snapshot data. public void setReadConnectionService( string $connectionService ) Sets the DependencyInjection connection service name used to read data public void setSnapshotData(array $data,mixed $columnMap = null) Sets the record's snapshot data. public ModelInterface setSync(mixed $elements = null,bool $enabled = true) Marks one or more many-to-many relationships to be synchronized (or not) public ModelInterface setTransaction( TransactionInterface $transaction ) Sets a transaction related to the Model instance public void setWriteConnectionService( string $connectionService ) Sets the DependencyInjection connection service name used to write data public void setup( array $options ) Enables/disables options in the ORM. public void skipOperation( bool $skip ) Skips the current operation forcing a success state public double|ResultsetInterface sum( mixed $parameters = null ) Calculates the sum on a column for a result-set of rows that match the public array toArray(mixed $columns = null,mixed $useGetter = true) Returns the instance as an array representation public void unserialize( string $data ) Unserializes the object from a serialized string public bool update() Updates a model instance. If the instance does not exist in the public bool validationHasFailed() Check whether validation process has generated any messages public void writeAttribute(string $attribute,mixed $value) Writes an attribute value by its name protected void allowEmptyStringValues( array $attributes ) Sets a list of attributes that must be skipped from the protected Relation belongsTo(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a reverse 1-1 or n-1 relation between two models protected cancelOperation() Cancel the current operation protected bool checkForeignKeysRestrict() Reads "belongs to" relations and check the virtual foreign keys when protected bool checkForeignKeysReverseCascade() Reads both "hasMany" and "hasOne" relations and checks the virtual protected bool checkForeignKeysReverseRestrict() Reads both "hasMany" and "hasOne" relations and checks the virtual protected array collectRelatedToSave() Collects previously queried (belongs-to, has-one and has-one-through) protected bool doLowInsert(MetaDataInterface $metaData,AdapterInterface $connection,mixed $table,mixed $identityField) Sends a pre-build INSERT SQL statement to the relational database system protected bool doLowUpdate(MetaDataInterface $metaData,AdapterInterface $connection,mixed $table) Sends a pre-build UPDATE SQL statement to the relational database system protected getRelatedRecords(string $modelName,string $method,array $arguments) Returns related records defined relations depending on the method name. protected mixed groupResult(string $functionName,string $alias,mixed $parameters = null) Generate a PHQL SELECT statement for an aggregate protected bool has(MetaDataInterface $metaData,AdapterInterface $connection) Checks whether the current record already exists protected Relation hasMany(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a 1-n relation between two models protected Relation hasManyToMany(mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referenceModel,mixed $referencedFields,array $options = []) Setup an n-n relation between two models, through an intermediate protected Relation hasOne(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models protected Relation hasOneThrough(mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referenceModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models, through an intermediate protected invokeFinder(string $method,array $arguments) Try to check if the query must invoke a finder protected void keepSnapshots( bool $keepSnapshot ) Sets if the model must keep the original record snapshot in memory protected bool possibleSetter(string $property,mixed $value) Check for, and attempt to use, possible setter. protected bool postSave(bool $success,bool $exists) Executes internal events after save a record protected bool postSaveRelatedRecords(AdapterInterface $connection,mixed $related,CollectionInterface $visited) Save the related records assigned in the has-one/has-many relations protected bool preSave(MetaDataInterface $metaData,bool $exists,mixed $identityField) Executes internal hooks before save a record protected bool preSaveRelatedRecords(AdapterInterface $connection,mixed $related,CollectionInterface $visited) Saves related records that must be stored prior to save the master record protected ModelInterface setSchema( string $schema ) Sets schema name where the mapped table is located protected ModelInterface setSource( string $source ) Sets the table name to which model should be mapped protected void skipAttributes( array $attributes ) Sets a list of attributes that must be skipped from the protected void skipAttributesOnCreate( array $attributes ) Sets a list of attributes that must be skipped from the protected void skipAttributesOnUpdate( array $attributes ) Sets a list of attributes that must be skipped from the protected void useDynamicUpdate( bool $dynamicUpdate ) Sets if a model must use dynamic update instead of the all-field update protected bool validate( ValidationInterface $validator ) Executes validators on every validation call Constants¶
int DIRTY_STATE_DETACHED = 2 int DIRTY_STATE_PERSISTENT = 0 int DIRTY_STATE_TRANSIENT = 1 int OP_CREATE = 1 int OP_DELETE = 3 int OP_NONE = 0 int OP_UPDATE = 2 string TRANSACTION_INDEX = "transaction" Properties¶
protected array $dirtyRelated = [] protected int $dirtyState = 1 protected array $errorMessages = [] protected ManagerInterface|null $modelsManager = null protected MetaDataInterface|null $modelsMetaData = null protected array $oldSnapshot = [] protected int $operationMade = 0 protected array $rawValues = [] protected array $related = [] protected bool $skipped = false protected array $snapshot = [] protected array $syncRelated = [] Per-save many-to-many sync overrides, keyed by lowercased relation alias (or "*" wildcard) => bool. Cleared after each save(). protected TransactionInterface|null $transaction = null protected string|null $uniqueKey = null protected array $uniqueParams = [] protected array $uniqueTypes = [] Methods¶
__call()¶
Handles method calls when a method is not implemented
__callStatic()¶
Handles method calls when a static method is not implemented
__construct()¶
final public function __construct(
mixed $data = null,
DiInterface $container = null,
ManagerInterface $modelsManager = null
);
Phalcon\Mvc\Model constructor
__get()¶
Magic method to get related records using the relation alias as a property
__isset()¶
Magic method to check if a property is a valid relation
__serialize()¶
Serializes a model
__set()¶
Magic method to assign values to the the model
__unserialize()¶
Unserializes an array to the model
addBehavior()¶
Setups a behavior in a model
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;
class Robots extends Model
{
public function initialize()
{
$this->addBehavior(
new Timestampable(
[
"beforeCreate" => [
"field" => "created_at",
"format" => "Y-m-d",
],
]
)
);
$this->addBehavior(
new Timestampable(
[
"beforeUpdate" => [
"field" => "updated_at",
"format" => "Y-m-d",
],
]
)
);
}
}
appendMessage()¶
Appends a customized message on the validation process
use Phalcon\Mvc\Model;
use Phalcon\Messages\Message as Message;
class Robots extends Model
{
public function beforeSave()
{
if ($this->name === "Peter") {
$message = new Message(
"Sorry, but a robot cannot be named Peter"
);
$this->appendMessage($message);
}
}
}
appendMessagesFrom()¶
** Append messages to this model from another Model.
assign()¶
public function assign(
array $data,
mixed $whiteList = null,
mixed $dataColumnMap = null
): ModelInterface;
Assigns values to a model from an array
$robot->assign(
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
// Assign by db row, column map needed
$robot->assign(
$dbRow,
[
"db_type" => "type",
"db_name" => "name",
"db_year" => "year",
]
);
// Allow assign only name and year
$robot->assign(
$_POST,
[
"name",
"year",
]
);
// By default assign method will use setters if exist, you can disable it by using ini_set to directly use properties
ini_set("phalcon.orm.disable_assign_setters", true);
$robot->assign(
$_POST,
[
"name",
"year",
]
);
average()¶
Returns the average value on a column for a result-set of rows matching the specified conditions.
Returned value will be a float for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the average of each group.
// What's the average price of robots?
$average = Robots::average(
[
"column" => "price",
]
);
echo "The average price is ", $average, "\n";
// What's the average price of mechanical robots?
$average = Robots::average(
[
"type = 'mechanical'",
"column" => "price",
]
);
echo "The average price of mechanical robots is ", $average, "\n";
cloneResult()¶
public static function cloneResult(
ModelInterface $base,
array $data,
int $dirtyState = 0
): ModelInterface;
Assigns values to a model from an array returning a new model
$robot = Phalcon\Mvc\Model::cloneResult(
new Robots(),
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
cloneResultMap()¶
public static function cloneResultMap(
mixed $base,
array $data,
mixed $columnMap,
int $dirtyState = 0,
bool $keepSnapshots = null
): ModelInterface;
Assigns values to a model from an array, returning a new model.
$robot = \Phalcon\Mvc\Model::cloneResultMap(
new Robots(),
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
cloneResultMapHydrate()¶
Returns an hydrated result based on the data and the column map
count()¶
Counts how many records match the specified conditions.
Returns an integer for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the count of each group.
// How many robots are there?
$number = Robots::count();
echo "There are ", $number, "\n";
// How many mechanical robots are there?
$number = Robots::count("type = 'mechanical'");
echo "There are ", $number, " mechanical robots\n";
create()¶
Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise.
// Creating a new robot
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
$robot->create();
// Passing an array to create
$robot = new Robots();
$robot->assign(
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
$robot->create();
delete()¶
Deletes a model instance. Returning true on success or false otherwise.
$robot = Robots::findFirst("id=100");
$robot->delete();
$robots = Robots::find("type = 'mechanical'");
foreach ($robots as $robot) {
$robot->delete();
}
doSave()¶
Inserted or updates model instance, expects a visited list of objects.
dump()¶
Returns a simple representation of the object that can be used with var_dump()
find()¶
Query for a set of records that match the specified conditions
// How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";
// How many mechanical robots are there?
$robots = Robots::find(
"type = 'mechanical'"
);
echo "There are ", count($robots), "\n";
// Get and print virtual robots ordered by name
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// Get first 100 virtual robots ordered by name
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
"limit" => 100,
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// encapsulate find it into an running transaction esp. useful for application unit-tests
// or complex business logic where we wanna control which transactions are used.
$myTransaction = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newRobot->save();
$resultInsideTransaction = Robot::find(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$resultOutsideTransaction = Robot::find(['name' => 'test']);
foreach ($setInsideTransaction as $robot) {
echo $robot->name, "\n";
}
foreach ($setOutsideTransaction as $robot) {
echo $robot->name, "\n";
}
// reverts all not commited changes
$myTransaction->rollback();
// creating two different transactions
$myTransaction1 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction1->begin();
$myTransaction2 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction2->begin();
// add a new robots
$firstNewRobot = new Robot();
$firstNewRobot->setTransaction($myTransaction1);
$firstNewRobot->assign(
[
'name' => 'first-transaction-robot',
'type' => 'mechanical',
'year' => 1944,
]
);
$firstNewRobot->save();
$secondNewRobot = new Robot();
$secondNewRobot->setTransaction($myTransaction2);
$secondNewRobot->assign(
[
'name' => 'second-transaction-robot',
'type' => 'fictional',
'year' => 1984,
]
);
$secondNewRobot->save();
// this transaction will find the robot.
$resultInFirstTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the robot.
$resultInSecondTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
]
);
// this transaction won't find the robot.
$resultInFirstTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction will find the robot.
$resultInSecondTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
]
);
$transaction1->rollback();
$transaction2->rollback();
findFirst()¶
Query the first record that matches the specified conditions
// What's the first robot in robots table?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name;
// What's the first mechanical robot in robots table?
$robot = Robots::findFirst(
"type = 'mechanical'"
);
echo "The first mechanical robot name is ", $robot->name;
// Get first virtual robot ordered by name
$robot = Robots::findFirst(
[
"type = 'virtual'",
"order" => "name",
]
);
echo "The first virtual robot name is ", $robot->name;
// behaviour with transaction
$myTransaction = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newRobot->save();
$findsARobot = Robot::findFirst(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$doesNotFindARobot = Robot::findFirst(
[
'name' => 'test',
]
);
var_dump($findARobot);
var_dump($doesNotFindARobot);
$transaction->commit();
$doesFindTheRobotNow = Robot::findFirst(
[
'name' => 'test',
]
);
fireEvent()¶
Fires an event, implicitly calls behaviors and listeners in the events manager are notified
fireEventCancel()¶
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()¶
Returns a list of changed values.
$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []
$robots->deleted = 'Y';
$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]
getDirtyState()¶
Returns one of the DIRTY_STATE_* constants telling if the record exists in the database or not
getEventsManager()¶
Returns the custom events manager or null if there is no custom events manager
getMessages()¶
Returns array of validation messages
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() === false) {
echo "Umh, We can't store robots right now ";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message;
}
} else {
echo "Great, a new robot was saved successfully!";
}
getModelsManager()¶
Returns the models manager related to the entity instance
getModelsMetaData()¶
{@inheritdoc}
getOldSnapshotData()¶
Returns the internal old snapshot data
getOperationMade()¶
Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants
getReadConnection()¶
Gets the connection used to read data for the model
getReadConnectionService()¶
Returns the DependencyInjection connection service name used to read data related the model
getRelated()¶
Returns related records based on defined relations
getSchema()¶
Returns schema name where the mapped table is located
getSnapshotData()¶
Returns the internal snapshot data
getSource()¶
Returns the table name mapped in the model
getTransaction()¶
getUpdatedFields()¶
Returns a list of updated values.
$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []
$robots->deleted = 'Y';
$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]
$robots->save();
print_r($robots->getChangedFields()); // []
print_r($robots->getUpdatedFields()); // ["deleted"]
getWriteConnection()¶
Gets the connection used to write data to the model
getWriteConnectionService()¶
Returns the DependencyInjection connection service name used to write data related to the model
hasChanged()¶
Check if a specific attribute has changed This only works if the model is keeping data snapshots
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
$robot->create();
$robot->type = "hydraulic";
$hasChanged = $robot->hasChanged("type"); // returns true
$hasChanged = $robot->hasChanged(["type", "name"]); // returns true
$hasChanged = $robot->hasChanged(["type", "name"], true); // returns false
hasSnapshotData()¶
Checks if the object has internal snapshot data
hasUpdated()¶
Check if a specific attribute was updated This only works if the model is keeping data snapshots
isRelationshipLoaded()¶
Checks if saved related records have already been loaded.
Only returns true if the records were previously fetched through the model without any additional parameters.
$robot = Robots::findFirst();
var_dump($robot->isRelationshipLoaded('robotsParts')); // false
$robotsParts = $robot->getRobotsParts(['id > 0']);
var_dump($robot->isRelationshipLoaded('robotsParts')); // false
$robotsParts = $robot->getRobotsParts(); // or $robot->robotsParts
var_dump($robot->isRelationshipLoaded('robotsParts')); // true
$robot->robotsParts = [new RobotsParts()];
var_dump($robot->isRelationshipLoaded('robotsParts')); // false
jsonSerialize()¶
Serializes the object for json_encode
maximum()¶
Returns the maximum value of a column for a result-set of rows that match the specified conditions
// What is the maximum robot id?
$id = Robots::maximum(
[
"column" => "id",
]
);
echo "The maximum robot id is: ", $id, "\n";
// What is the maximum id of mechanical robots?
$sum = Robots::maximum(
[
"type = 'mechanical'",
"column" => "id",
]
);
echo "The maximum robot id of mechanical robots is ", $id, "\n";
minimum()¶
Returns the minimum value of a column for a result-set of rows that match the specified conditions
// What is the minimum robot id?
$id = Robots::minimum(
[
"column" => "id",
]
);
echo "The minimum robot id is: ", $id;
// What is the minimum id of mechanical robots?
$sum = Robots::minimum(
[
"type = 'mechanical'",
"column" => "id",
]
);
echo "The minimum robot id of mechanical robots is ", $id;
query()¶
Create a criteria for a specific model
readAttribute()¶
Reads an attribute value by its name
refresh()¶
Refreshes the model attributes re-querying the record from the database
save()¶
Inserts or updates a model instance. Returning true on success or false otherwise.
// Creating a new robot
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
$robot->save();
// Updating a robot name
$robot = Robots::findFirst("id = 100");
$robot->name = "Biomass";
$robot->save();
serialize()¶
Serializes the object ignoring connections, services, related objects or static properties
setConnectionService()¶
Sets the DependencyInjection connection service name
setDirtyState()¶
Sets the dirty state of the object using one of the DIRTY_STATE_* constants
setEventsManager()¶
Sets a custom events manager
setOldSnapshotData()¶
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()¶
Sets the DependencyInjection connection service name used to read data
setSnapshotData()¶
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()¶
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()¶
Sets a transaction related to the Model instance
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
try {
$txManager = new TxManager();
$transaction = $txManager->get();
$robot = new Robots();
$robot->setTransaction($transaction);
$robot->name = "WALL·E";
$robot->created_at = date("Y-m-d");
if ($robot->save() === false) {
$transaction->rollback("Can't save robot");
}
$robotPart = new RobotParts();
$robotPart->setTransaction($transaction);
$robotPart->type = "head";
if ($robotPart->save() === false) {
$transaction->rollback("Robot part cannot be saved");
}
$transaction->commit();
} catch (TxFailed $e) {
echo "Failed, reason: ", $e->getMessage();
}
setWriteConnectionService()¶
Sets the DependencyInjection connection service name used to write data
setup()¶
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()¶
Skips the current operation forcing a success state
sum()¶
Calculates the sum on a column for a result-set of rows that match the specified conditions
// How much are all robots?
$sum = Robots::sum(
[
"column" => "price",
]
);
echo "The total price of robots is ", $sum, "\n";
// How much are mechanical robots?
$sum = Robots::sum(
[
"type = 'mechanical'",
"column" => "price",
]
);
echo "The total price of mechanical robots is ", $sum, "\n";
toArray()¶
Returns the instance as an array representation
unserialize()¶
Unserializes the object from a serialized string
update()¶
Updates a model instance. If the instance does not exist in the persistence it will throw an exception. Returning true on success or false otherwise.
<?php
use MyApp\Models\Invoices;
$invoice = Invoices::findFirst('inv_id = 4');
$invoice->inv_total = 120;
$invoice->update();
NOTE
When retrieving the record with findFirst(), you need to get the full object back (no columns definition) but also retrieve it using the primary key. If not, the ORM will issue an INSERT instead of UPDATE.
validationHasFailed()¶
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()¶
Writes an attribute value by its name
allowEmptyStringValues()¶
Sets a list of attributes that must be skipped from the generated UPDATE statement
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->allowEmptyStringValues(
[
"name",
]
);
}
}
belongsTo()¶
protected function belongsTo(
mixed $fields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup a reverse 1-1 or n-1 relation between two models
class RobotsParts extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->belongsTo(
"robots_id",
Robots::class,
"id"
);
}
}
cancelOperation()¶
Cancel the current operation
checkForeignKeysRestrict()¶
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()¶
Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (cascade) when deleting records
checkForeignKeysReverseRestrict()¶
Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (restrict) when deleting records
collectRelatedToSave()¶
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()¶
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()¶
Checks whether the current record already exists
hasMany()¶
protected function hasMany(
mixed $fields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup a 1-n relation between two models
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany(
"id",
RobotsParts::class,
"robots_id"
);
}
}
hasManyToMany()¶
protected function hasManyToMany(
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup an n-n relation between two models, through an intermediate relation
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
// Setup a many-to-many relation to Parts through RobotsParts
$this->hasManyToMany(
"id",
RobotsParts::class,
"robots_id",
"parts_id",
Parts::class,
"id",
);
}
}
hasOne()¶
protected function hasOne(
mixed $fields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup a 1-1 relation between two models
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasOne(
"id",
RobotsDescription::class,
"robots_id"
);
}
}
hasOneThrough()¶
protected function hasOneThrough(
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup a 1-1 relation between two models, through an intermediate relation
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
// Setup a 1-1 relation to one item from Parts through RobotsParts
$this->hasOneThrough(
"id",
RobotsParts::class,
"robots_id",
"parts_id",
Parts::class,
"id",
);
}
}
invokeFinder()¶
Try to check if the query must invoke a finder
keepSnapshots()¶
Sets if the model must keep the original record snapshot in memory
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->keepSnapshots(true);
}
}
possibleSetter()¶
Check for, and attempt to use, possible setter.
postSave()¶
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()¶
Sets schema name where the mapped table is located
setSource()¶
Sets the table name to which model should be mapped
skipAttributes()¶
Sets a list of attributes that must be skipped from the generated INSERT/UPDATE statement
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->skipAttributes(
[
"price",
]
);
}
}
skipAttributesOnCreate()¶
Sets a list of attributes that must be skipped from the generated INSERT statement
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->skipAttributesOnCreate(
[
"created_at",
]
);
}
}
skipAttributesOnUpdate()¶
Sets a list of attributes that must be skipped from the generated UPDATE statement
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->skipAttributesOnUpdate(
[
"modified_in",
]
);
}
}
useDynamicUpdate()¶
Sets if a model must use dynamic update instead of the all-field update
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->useDynamicUpdate(true);
}
}
validate()¶
Executes validators on every validation call
use Phalcon\Mvc\Model;
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\ExclusionIn;
class Subscriptors extends Model
{
public function validation()
{
$validator = new Validation();
$validator->add(
"status",
new ExclusionIn(
[
"domain" => [
"A",
"I",
],
]
)
);
return $this->validate($validator);
}
}
Mvc\ModelInterface¶
Interface Source on GitHub
Phalcon\Mvc\ModelInterface
Interface for Phalcon\Mvc\Model
@template T
Phalcon\Mvc\ModelInterface
Uses Phalcon\Db\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Messages\MessageInterface · Phalcon\Mvc\Model\CriteriaInterface · Phalcon\Mvc\Model\MetaDataInterface · Phalcon\Mvc\Model\ResultInterface · Phalcon\Mvc\Model\Resultset · Phalcon\Mvc\Model\ResultsetInterface · Phalcon\Mvc\Model\TransactionInterface
Method Summary¶
public ModelInterface appendMessage( MessageInterface $message ) Appends a customized message on the validation process public ModelInterface assign(array $data,mixed $whiteList = null,mixed $dataColumnMap = null) Assigns values to a model from an array public double|ResultsetInterface average( array $parameters = [] ) Allows to calculate the average value on a column matching the specified public ModelInterface cloneResult(ModelInterface $base,array $data,int $dirtyState = 0) Assigns values to a model from an array returning a new model public ModelInterface cloneResultMap(mixed $base,array $data,mixed $columnMap,int $dirtyState = 0,bool $keepSnapshots = false) Assigns values to a model from an array returning a new model public cloneResultMapHydrate(array $data,mixed $columnMap,int $hydrationMode) Returns an hydrated result based on the data and the column map public int|ResultsetInterface count( mixed $parameters = null ) Allows to count how many records match the specified conditions public bool create() Inserts a model instance. If the instance already exists in the public bool delete() Deletes a model instance. Returning true on success or false otherwise. public find( mixed $parameters = null ) Allows to query a set of records that match the specified conditions. public mixed|null findFirst( mixed $parameters = null ) Allows to query the first record that match the specified conditions public bool fireEvent( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public bool fireEventCancel( string $eventName ) Fires an event, implicitly calls behaviors and listeners in the events public int getDirtyState() Returns one of the DIRTY_STATE_* constants telling if the record exists public MessageInterface[] getMessages() Returns array of validation messages public MetaDataInterface getModelsMetaData() Returns the models meta-data service related to the entity instance. public int getOperationMade() Returns the type of the latest operation performed by the ORM public AdapterInterface getReadConnection() Gets internal database connection public string getReadConnectionService() Returns DependencyInjection connection service used to read data public getRelated(string $alias,mixed $arguments = null) Returns related records based on defined relations public string|null getSchema() Returns schema name where table mapped is located public string getSource() Returns table name mapped in the model public AdapterInterface getWriteConnection() Gets internal database connection public string getWriteConnectionService() Returns DependencyInjection connection service used to write data public mixed maximum( mixed $parameters = null ) Allows to get the maximum value of a column that match the specified public mixed minimum( mixed $parameters = null ) Allows to get the minimum value of a column that match the specified public CriteriaInterface query( DiInterface $container = null ) Create a criteria for a specific model public ModelInterface refresh() Refreshes the model attributes re-querying the record from the database public bool save() Inserts or updates a model instance. Returning true on success or false public void setConnectionService( string $connectionService ) Sets both read/write connection services public ModelInterface|bool setDirtyState( int $dirtyState ) Sets the dirty state of the object using one of the DIRTY_STATE_* public void setReadConnectionService( string $connectionService ) Sets the DependencyInjection connection service used to read data public void setSnapshotData(array $data,mixed $columnMap = null) Sets the record's snapshot data. This method is used internally to set public ModelInterface setSync(mixed $elements = null,bool $enabled = true) Marks one or more many-to-many relationships to be synchronized (or not) public ModelInterface setTransaction( TransactionInterface $transaction ) Sets a transaction related to the Model instance public void setWriteConnectionService( string $connectionService ) Sets the DependencyInjection connection service used to write data public void skipOperation( bool $skip ) Skips the current operation forcing a success state public double|ResultsetInterface sum( mixed $parameters = null ) Allows to calculate a sum on a column that match the specified conditions public bool update() Updates a model instance. If the instance does not exist in the public bool validationHasFailed() Check whether validation process has generated any messages Methods¶
appendMessage()¶
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()¶
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()¶
Returns an hydrated result based on the data and the column map
count()¶
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()¶
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()¶
Deletes a model instance. Returning true on success or false otherwise.
find()¶
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\Builderas the canonical programmatic API;Phalcon\Mvc\Model\Criteriaas request-bound convenience;- raw PHQL via
Phalcon\Mvc\Model\Queryfor everything else.
findFirst()¶
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()¶
Fires an event, implicitly calls behaviors and listeners in the events manager are notified
fireEventCancel()¶
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()¶
Returns one of the DIRTY_STATE_* constants telling if the record exists in the database or not
getMessages()¶
Returns array of validation messages
getModelsMetaData()¶
Returns the models meta-data service related to the entity instance.
getOperationMade()¶
Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants
getReadConnection()¶
Gets internal database connection
getReadConnectionService()¶
Returns DependencyInjection connection service used to read data
getRelated()¶
Returns related records based on defined relations
getSchema()¶
Returns schema name where table mapped is located
getSource()¶
Returns table name mapped in the model
getWriteConnection()¶
Gets internal database connection
getWriteConnectionService()¶
Returns DependencyInjection connection service used to write data
maximum()¶
Allows to get the maximum value of a column that match the specified conditions
minimum()¶
Allows to get the minimum value of a column that match the specified conditions
query()¶
Create a criteria for a specific model
refresh()¶
Refreshes the model attributes re-querying the record from the database
save()¶
Inserts or updates a model instance. Returning true on success or false otherwise.
setConnectionService()¶
Sets both read/write connection services
setDirtyState()¶
Sets the dirty state of the object using one of the DIRTY_STATE_* constants
setReadConnectionService()¶
Sets the DependencyInjection connection service used to read data
setSnapshotData()¶
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()¶
Marks one or more many-to-many relationships to be synchronized (or not) on the next save() call.
setTransaction()¶
Sets a transaction related to the Model instance
setWriteConnectionService()¶
Sets the DependencyInjection connection service used to write data
skipOperation()¶
Skips the current operation forcing a success state
sum()¶
Allows to calculate a sum on a column that match the specified conditions
update()¶
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()¶
Check whether validation process has generated any messages
Mvc\Model\Behavior¶
Abstract Source on GitHub
Phalcon\Mvc\Model\Behavior
This is an optional base class for ORM behaviors
Phalcon\Mvc\Model\Behavior— implementsPhalcon\Mvc\Model\BehaviorInterface
Uses Phalcon\Mvc\ModelInterface
Method Summary¶
public __construct( array $options = [] ) Phalcon\Mvc\Model\Behavior public missingMethod(ModelInterface $model,string $method,array $arguments = []) Acts as fallbacks when a missing method is called on the model public notify(string $type,ModelInterface $model) This method receives the notifications from the EventsManager protected getOptions( string $eventName = null ) Returns the behavior options related to an event protected bool mustTakeAction( string $eventName ) Checks whether the behavior must take action on certain event Properties¶
protected array $options Methods¶
__construct()¶
Phalcon\Mvc\Model\Behavior
missingMethod()¶
Acts as fallbacks when a missing method is called on the model
notify()¶
This method receives the notifications from the EventsManager
getOptions()¶
Returns the behavior options related to an event
mustTakeAction()¶
Checks whether the behavior must take action on certain event
Mvc\Model\BehaviorInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\BehaviorInterface
Interface for Phalcon\Mvc\Model\Behavior
Phalcon\Mvc\Model\BehaviorInterface
Uses Phalcon\Mvc\ModelInterface
Method Summary¶
public missingMethod(ModelInterface $model,string $method,array $arguments = []) Calls a method when it's missing in the model public notify(string $type,ModelInterface $model) This method receives the notifications from the EventsManager Methods¶
missingMethod()¶
Calls a method when it's missing in the model
notify()¶
This method receives the notifications from the EventsManager
Mvc\Model\Behavior\Exceptions\MissingRequiredOption¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Behavior\Exceptions\MissingRequiredOption
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Behavior\SoftDelete¶
Class Source on GitHub
Phalcon\Mvc\Model\Behavior\SoftDelete
Instead of permanently delete a record it marks the record as deleted changing the value of a flag column
Phalcon\Mvc\Model\BehaviorPhalcon\Mvc\Model\Behavior\SoftDelete
Uses Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Behavior · Phalcon\Mvc\Model\Behavior\Exceptions\MissingRequiredOption · Phalcon\Mvc\Model\Exception · Phalcon\Support\Settings
Method Summary¶
Methods¶
notify()¶
Listens for notifications from the models manager
Mvc\Model\Behavior\Timestampable¶
Class Source on GitHub
Phalcon\Mvc\Model\Behavior\Timestampable
Allows to automatically update a model’s attribute saving the datetime when a record is created or updated
Phalcon\Mvc\Model\BehaviorPhalcon\Mvc\Model\Behavior\Timestampable
Uses Closure · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Behavior · Phalcon\Mvc\Model\Behavior\Exceptions\MissingRequiredOption · Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
notify()¶
Listens for notifications from the models manager
Mvc\Model\Binder¶
Class Source on GitHub
Phalcon\Mvc\Model\Binder
This is an class for binding models into params for handler
Phalcon\Mvc\Model\Binder— implementsPhalcon\Mvc\Model\BinderInterface
Uses Closure · Phalcon\Cache\Adapter\AdapterInterface · Phalcon\Mvc\Controller\BindModelInterface · Phalcon\Mvc\Model\Binder\BindableInterface · Phalcon\Mvc\Model\Exceptions\HandlerMustImplementBindable · Phalcon\Mvc\Model\Exceptions\InvalidGetModelNameReturn · Phalcon\Mvc\Model\Exceptions\MissingMethodName · Phalcon\Mvc\Model\Exceptions\MissingModelClassName · ReflectionFunction · ReflectionMethod · ReflectionNamedType
Method Summary¶
public __construct( AdapterInterface $cache = null ) Phalcon\Mvc\Model\Binder constructor public array bindToHandler(object $handler,array $params,string $cacheKey,string $methodName = null) Bind models into params in proper handler public array getBoundModels() Return the active bound models public AdapterInterface getCache() Sets cache instance public array getOriginalValues() Return the array for original values public BinderInterface setCache( AdapterInterface $cache ) Gets cache instance protected mixed|bool findBoundModel(mixed $paramValue,string $className) Find the model by param value. protected array|null getParamsFromCache( string $cacheKey ) Get params classes from cache by key protected array getParamsFromReflection(object $handler,array $params,string $cacheKey,string $methodName) Get modified params for handler using reflection Properties¶
protected array $boundModels = [] Array for storing active bound models protected AdapterInterface|null $cache Cache object used for caching parameters for model binding protected array $internalCache = [] Internal cache for caching parameters for model binding during request protected array $originalValues = [] Array for original values Methods¶
__construct()¶
Phalcon\Mvc\Model\Binder constructor
bindToHandler()¶
public function bindToHandler(
object $handler,
array $params,
string $cacheKey,
string $methodName = null
): array;
Bind models into params in proper handler
getBoundModels()¶
Return the active bound models
getCache()¶
Sets cache instance
getOriginalValues()¶
Return the array for original values
setCache()¶
Gets cache instance
findBoundModel()¶
Find the model by param value.
getParamsFromCache()¶
Get params classes from cache by key
getParamsFromReflection()¶
protected function getParamsFromReflection(
object $handler,
array $params,
string $cacheKey,
string $methodName
): array;
Get modified params for handler using reflection
Mvc\Model\BinderInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\BinderInterface
Interface for Phalcon\Mvc\Model\Binder
Phalcon\Mvc\Model\BinderInterface
Uses Phalcon\Cache\Adapter\AdapterInterface
Method Summary¶
public array bindToHandler(object $handler,array $params,string $cacheKey,string $methodName = null) Bind models into params in proper handler public array getBoundModels() Gets active bound models public AdapterInterface getCache() Gets cache instance public BinderInterface setCache( AdapterInterface $cache ) Sets cache instance Methods¶
bindToHandler()¶
public function bindToHandler(
object $handler,
array $params,
string $cacheKey,
string $methodName = null
): array;
Bind models into params in proper handler
getBoundModels()¶
Gets active bound models
getCache()¶
Gets cache instance
setCache()¶
Sets cache instance
Mvc\Model\Binder\BindableInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\Binder\BindableInterface
Interface for bindable classes
Phalcon\Mvc\Model\Binder\BindableInterface
Method Summary¶
Methods¶
getModelName()¶
Return the model name or models names and parameters keys associated with this class
Mvc\Model\Criteria¶
Class Source on GitHub
This class is used to build the array parameter required by Phalcon\Mvc\Model::find() and Phalcon\Mvc\Model::findFirst() using an object-oriented interface.
<?php
$invoices = Invoices::query()
->where("inv_cst_id = :customerId:")
->andWhere("inv_created_date < '2000-01-01'")
->bind(["customerId" => 1])
->limit(5, 10)
->orderBy("inv_title")
->execute();
Phalcon\Mvc\Model\Criteria— implementsPhalcon\Mvc\Model\CriteriaInterface,Phalcon\Di\InjectionAwareInterface
Uses Phalcon\Db\Column · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\Model\Exceptions\InvalidModelName · Phalcon\Mvc\Model\Query\BuilderInterface
Method Summary¶
public CriteriaInterface andWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an AND operator public CriteriaInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a BETWEEN condition to the current conditions public CriteriaInterface bind(array $bindParams,bool $merge = false) Sets the bound parameters in the criteria public CriteriaInterface bindTypes( array $bindTypes ) Sets the bind types in the criteria public CriteriaInterface cache( array $cache ) Sets the cache options in the criteria public CriteriaInterface columns( mixed $columns ) Sets the columns to be queried. The columns can be either a string or public CriteriaInterface conditions( string $conditions ) Adds the conditions parameter to the criteria public BuilderInterface createBuilder() Creates a query builder from criteria. public CriteriaInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public ResultsetInterface execute() Executes a find using the parameters built with the criteria public CriteriaInterface forUpdate( bool $forUpdate = true ) Adds the "for_update" parameter to the criteria public CriteriaInterface fromInput(DiInterface $container,string $modelName,array $data,string $operator = "AND") Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST public string|array|null getColumns() Returns the columns to be queried public string|null getConditions() Returns the conditions parameter in the criteria public DiInterface getDI() Returns the DependencyInjector container public getGroupBy() Returns the group clause in the criteria public getHaving() Returns the having clause in the criteria public int|array|null getLimit() Returns the limit parameter in the criteria, which will be public string getModelName() Returns an internal model name on which the criteria will be applied public string|null getOrderBy() Returns the order clause in the criteria public array getParams() Returns all the parameters defined in the criteria public string|null getWhere() Returns the conditions parameter in the criteria public CriteriaInterface groupBy( mixed $group ) Adds the group-by clause to the criteria public CriteriaInterface having( mixed $having ) Adds the having clause to the criteria public CriteriaInterface inWhere(string $expr,array $values) Appends an IN condition to the current conditions public CriteriaInterface innerJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds an INNER join to the query public CriteriaInterface join(string $model,mixed $conditions = null,mixed $alias = null,mixed $type = null) Adds an INNER join to the query public CriteriaInterface leftJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a LEFT join to the query public CriteriaInterface limit(int $limit,int $offset = 0) Adds the limit parameter to the criteria. public CriteriaInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a NOT BETWEEN condition to the current conditions public CriteriaInterface notInWhere(string $expr,array $values) Appends a NOT IN condition to the current conditions public CriteriaInterface orWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an OR operator public CriteriaInterface orderBy( string $orderColumns ) Adds the order-by clause to the criteria public CriteriaInterface rightJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a RIGHT join to the query public void setDI( DiInterface $container ) Sets the DependencyInjector container public CriteriaInterface setModelName( string $modelName ) Set a model on which the query will be executed public CriteriaInterface sharedLock( bool $sharedLock = true ) Adds the "shared_lock" parameter to the criteria public CriteriaInterface where(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Sets the conditions parameter in the criteria Properties¶
protected array $bindParams protected array $bindTypes protected int $hiddenParamNumber = 0 protected string|null $model = null protected array $params = [] Methods¶
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()¶
Appends a BETWEEN condition to the current conditions
bind()¶
Sets the bound parameters in the criteria This method replaces all previously set bound parameters
bindTypes()¶
Sets the bind types in the criteria This method replaces all previously set bound parameters
cache()¶
Sets the cache options in the criteria This method replaces all previously set cache options
columns()¶
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()¶
Adds the conditions parameter to the criteria
createBuilder()¶
Creates a query builder from criteria.
where("inv_cst_id = :customerId:") ->bind(["customerId" => 1]) ->createBuilder();#### `distinct()` { #mvcmodelcriteria-distinct }
```php
public function distinct( mixed $distinct ): CriteriaInterface;
public static function fromInput(
DiInterface $container,
string $modelName,
array $data,
string $operator = "AND"
): CriteriaInterface;
public function innerJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
<?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"
);
public function join(
string $model,
mixed $conditions = null,
mixed $alias = null,
mixed $type = null
): CriteriaInterface;
<?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"
);
public function leftJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
public function orWhere(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
public function rightJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
public function where(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
public CriteriaInterface andWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an AND operator public CriteriaInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a BETWEEN condition to the current conditions public CriteriaInterface bind( array $bindParams ) Sets the bound parameters in the criteria public CriteriaInterface bindTypes( array $bindTypes ) Sets the bind types in the criteria public CriteriaInterface cache( array $cache ) Sets the cache options in the criteria public CriteriaInterface conditions( string $conditions ) Adds the conditions parameter to the criteria public CriteriaInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public ResultsetInterface execute() Executes a find using the parameters built with the criteria public CriteriaInterface forUpdate( bool $forUpdate = true ) Sets the "for_update" parameter to the criteria public string|array|null getColumns() Returns the columns to be queried public string|null getConditions() Returns the conditions parameter in the criteria public getGroupBy() Returns the group clause in the criteria public getHaving() Returns the having clause in the criteria public int|array|null getLimit() Returns the limit parameter in the criteria, which will be public string getModelName() Returns an internal model name on which the criteria will be applied public string|null getOrderBy() Returns the order parameter in the criteria public array getParams() Returns all the parameters defined in the criteria public string|null getWhere() Returns the conditions parameter in the criteria public CriteriaInterface groupBy( mixed $group ) Adds the group-by clause to the criteria public CriteriaInterface having( mixed $having ) Adds the having clause to the criteria public CriteriaInterface inWhere(string $expr,array $values) Appends an IN condition to the current conditions public CriteriaInterface innerJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds an INNER join to the query public CriteriaInterface leftJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a LEFT join to the query public CriteriaInterface limit(int $limit,int $offset = 0) Sets the limit parameter to the criteria public CriteriaInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum) Appends a NOT BETWEEN condition to the current conditions public CriteriaInterface notInWhere(string $expr,array $values) Appends a NOT IN condition to the current conditions public CriteriaInterface orWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Appends a condition to the current conditions using an OR operator public CriteriaInterface orderBy( string $orderColumns ) Adds the order-by parameter to the criteria public CriteriaInterface rightJoin(string $model,mixed $conditions = null,mixed $alias = null) Adds a RIGHT join to the query public CriteriaInterface setModelName( string $modelName ) Set a model on which the query will be executed public CriteriaInterface sharedLock( bool $sharedLock = true ) Sets the "shared_lock" parameter to the criteria public CriteriaInterface where(string $conditions,mixed $bindParams = null,mixed $bindTypes = null) Sets the conditions parameter in the criteria public function andWhere(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
public function innerJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
$criteria->innerJoin(
Robots::class
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id"
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
public function leftJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
public function orWhere(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
public function rightJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
public function where(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
use Phalcon\Di\Di;
use Phalcon\Mvc\Model\Manager as ModelsManager;
$di = new Di();
$di->set(
"modelsManager",
function() {
return new ModelsManager();
}
);
$robot = new Robots($di);
public __destruct() Destroys the current PHQL cache public void addBehavior(ModelInterface $model,BehaviorInterface $behavior) Binds a behavior to a model public RelationInterface addBelongsTo(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation reverse many to one between two models public RelationInterface addHasMany(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation 1-n between two models public RelationInterface addHasManyToMany(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a relation n-m between two models public RelationInterface addHasOne(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models public RelationInterface addHasOneThrough(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a relation 1-1 between two models using an intermediate model public void clearReusableObjects() Clears the internal reusable list public BuilderInterface createBuilder( mixed $params = null ) Creates a Phalcon\Mvc\Model\Query\Builder public QueryInterface createQuery( string $phql ) Creates a Phalcon\Mvc\Model\Query without execute it public mixed executeQuery(string $phql,mixed $placeholders = null,mixed $types = null) Creates a Phalcon\Mvc\Model\Query and execute it public bool existsBelongsTo(string $modelName,string $modelRelation) Checks whether a model has a belongsTo relation with another model public bool existsHasMany(string $modelName,string $modelRelation) Checks whether a model has a hasMany relation with another model public bool existsHasManyToMany(string $modelName,string $modelRelation) Checks whether a model has a hasManyToMany relation with another model public bool existsHasOne(string $modelName,string $modelRelation) Checks whether a model has a hasOne relation with another model public bool existsHasOneThrough(string $modelName,string $modelRelation) Checks whether a model has a hasOneThrough relation with another model public RelationInterface[]|array getBelongsTo( ModelInterface $model ) Gets all the belongsTo relations defined in a model public ResultsetInterface|bool getBelongsToRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets belongsTo related records from a model public BuilderInterface|null getBuilder() Returns the newly created Phalcon\Mvc\Model\Query\Builder or null public string getConnectionService(ModelInterface $model,array $connectionServices) Returns the connection service name used to read or write data related to public EventsManagerInterface|null getCustomEventsManager( ModelInterface $model ) Returns a custom events manager related to a model or null if there is public DiInterface getDI() Returns the DependencyInjector container public EventsManagerInterface|null getEventsManager() Returns the internal event manager public RelationInterface[]|array getHasMany( ModelInterface $model ) Gets hasMany relations defined on a model public ResultsetInterface|bool getHasManyRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets hasMany related records from a model public RelationInterface[]|array getHasManyToMany( ModelInterface $model ) Gets hasManyToMany relations defined on a model public array getHasOne( ModelInterface $model ) Gets hasOne relations defined on a model public RelationInterface[] getHasOneAndHasMany( ModelInterface $model ) Gets hasOne relations defined on a model public ModelInterface|bool getHasOneRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets belongsTo related records from a model public RelationInterface[]|array getHasOneThrough( ModelInterface $model ) Gets hasOneThrough relations defined on a model public ModelInterface|null getLastInitialized() Get last initialized model public QueryInterface getLastQuery() Returns the last query created or executed in the models manager public string getModelPrefix() Returns the prefix for all model sources. public string|null getModelSchema( ModelInterface $model ) Returns the mapped schema for a model public string getModelSource( ModelInterface $model ) Returns the mapped source for a model public AdapterInterface getReadConnection( ModelInterface $model ) Returns the connection to read data related to a model public string getReadConnectionService( ModelInterface $model ) Returns the connection service name used to read data related to a model public RelationInterface|bool getRelationByAlias(string $modelName,string $alias) Returns a relation by its alias public getRelationRecords(RelationInterface $relation,ModelInterface $record,mixed $parameters = null,string $method = null) Helper method to query records based on a relation definition public RelationInterface[] getRelations( string $modelName ) Query all the relationships defined on a model public RelationInterface[]|bool getRelationsBetween(string $first,string $second) Query the first relationship defined between two models public getReusableRecords(string $modelName,string $key) Returns a reusable object from the internal list public AdapterInterface getWriteConnection( ModelInterface $model ) Returns the connection to write data related to a model public string getWriteConnectionService( ModelInterface $model ) Returns the connection service name used to write data related to a model public bool hasBelongsTo(string $modelName,string $modelRelation) Checks whether a model has a belongsTo relation with another model public bool hasHasMany(string $modelName,string $modelRelation) Checks whether a model has a hasMany relation with another model public bool hasHasManyToMany(string $modelName,string $modelRelation) Checks whether a model has a hasManyToMany relation with another model public bool hasHasOne(string $modelName,string $modelRelation) Checks whether a model has a hasOne relation with another model public bool hasHasOneThrough(string $modelName,string $modelRelation) Checks whether a model has a hasOneThrough relation with another model public bool initialize( ModelInterface $model ) Initializes a model in the model manager public bool isInitialized( string $className ) Check whether a model is already initialized public bool isKeepingSnapshots( ModelInterface $model ) Checks if a model is keeping snapshots for the queried records public bool isUsingDynamicUpdate( ModelInterface $model ) Checks if a model is using dynamic update instead of all-field update public bool isVisibleModelProperty(ModelInterface $model,string $property) Check whether a model property is declared as public. public void keepSnapshots(ModelInterface $model,bool $keepSnapshots) Sets if a model must keep snapshots public ModelInterface load( string $modelName ) Loads a model throwing an exception if it does not exist public missingMethod(ModelInterface $model,string $eventName,mixed $data) Dispatch an event to the listeners and behaviors public notifyEvent(string $eventName,ModelInterface $model) Receives events generated in the models and dispatches them to an public void removeBehavior(ModelInterface $model,string $behaviorClass) Removes a behavior from a model public void setConnectionService(ModelInterface $model,string $connectionService) Sets both write and read connection service for a model public void setCustomEventsManager(ModelInterface $model,EventsManagerInterface $eventsManager) Sets a custom events manager for a specific model public void setDI( DiInterface $container ) Sets the DependencyInjector container public void setEventsManager( EventsManagerInterface $eventsManager ) Sets a global events manager public void setModelPrefix( string $prefix ) Sets the prefix for all model sources. public void setModelSchema(ModelInterface $model,string $schema) Sets the mapped schema for a model public void setModelSource(ModelInterface $model,string $source) Sets the mapped source for a model public void setReadConnectionService(ModelInterface $model,string $connectionService) Sets read connection service for a model public void setReusableRecords(string $modelName,string $key,mixed $records) Stores a reusable record in the internal list public void setWriteConnectionService(ModelInterface $model,string $connectionService) Sets write connection service for a model public void useDynamicUpdate(ModelInterface $model,bool $dynamicUpdate) Sets if a model must use dynamic update instead of the all-field update protected AdapterInterface getConnection(ModelInterface $model,array $connectionServices) Returns the connection to read or write data related to a model protected array mergeFindParameters(mixed $findParamsOne,mixed $findParamsTwo) Merge two arrays of find parameters protected array $aliases = [] protected array $behaviors = [] Models' behaviors protected array $belongsTo = [] Belongs to relations protected array $belongsToSingle = [] All the relationships by model protected BuilderInterface|null $builder = null protected DiInterface|null $container = null protected array $customEventsManager = [] protected array $dynamicUpdate = [] Does the model use dynamic update, instead of updating all rows? protected EventsManagerInterface|null $eventsManager = null protected array $hasMany = [] Has many relations protected array $hasManySingle = [] Has many relations by model protected array $hasManyToMany = [] Has many-Through relations protected array $hasManyToManySingle = [] Has many-Through relations by model protected array $hasOne = [] Has one relations protected array $hasOneSingle = [] Has one relations by model protected array $hasOneThrough = [] Has one through relations protected array $hasOneThroughSingle = [] Has one through relations by model protected array $initialized = [] Mark initialized models protected array $keepSnapshots = [] protected ModelInterface|null $lastInitialized = null Last model initialized protected QueryInterface|null $lastQuery = null Last query created/executed protected array $modelVisibility = [] protected string $prefix = "" protected array $readConnectionServices = [] protected array $reusable = [] Stores a list of reusable instances protected array $schemas = [] protected array $sources = [] protected array $writeConnectionServices = [] public function addBelongsTo(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasMany(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasManyToMany(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasOne(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasOneThrough(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function executeQuery(
string $phql,
mixed $placeholders = null,
mixed $types = null
): mixed;
$model = new Robots();
$manager = $model->getModelsManager();
// \Phalcon\Mvc\Model\Resultset\Simple
$manager->executeQuery('SELECT * FROM Robots');
// \Phalcon\Mvc\Model\Resultset\Complex
$manager->executeQuery('SELECT COUNT(type) FROM Robots GROUP BY type');
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('INSERT INTO Robots (id) VALUES (1)');
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('UPDATE Robots SET id = 0 WHERE id = :id:', ['id' => 1]);
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('DELETE FROM Robots WHERE id = :id:', ['id' => 1]);
public function getBelongsToRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
public function getHasManyRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
public function getHasOneRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ModelInterface|bool;
public function getRelationRecords(
RelationInterface $relation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
);
public function setCustomEventsManager(
ModelInterface $model,
EventsManagerInterface $eventsManager
): void;
use Phalcon\Mvc\Model\Manager;
$di->set(
"modelsManager",
function () {
$modelsManager = new Manager();
$modelsManager->setModelPrefix("wp_");
return $modelsManager;
}
);
$robots = new Robots();
echo $robots->getSource(); // wp_robots
public function setWriteConnectionService(
ModelInterface $model,
string $connectionService
): void;
protected function getConnection(
ModelInterface $model,
array $connectionServices
): AdapterInterface;
public void addBehavior(ModelInterface $model,BehaviorInterface $behavior) Binds a behavior to a model public RelationInterface addBelongsTo(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation reverse 1-1 between two models public RelationInterface addHasMany(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a relation 1-n between two models public RelationInterface addHasManyToMany(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a relation n-m between two models public RelationInterface addHasOne(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = []) Setup a 1-1 relation between two models public RelationInterface addHasOneThrough(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = []) Setups a 1-1 relation between two models using an intermediate table public void clearReusableObjects() Clears the internal reusable list public BuilderInterface createBuilder( mixed $params = null ) Creates a Phalcon\Mvc\Model\Query\Builder public QueryInterface createQuery( string $phql ) Creates a Phalcon\Mvc\Model\Query without execute it public mixed executeQuery(string $phql,mixed $placeholders = null,mixed $types = null) Creates a Phalcon\Mvc\Model\Query and execute it public RelationInterface[]|array getBelongsTo( ModelInterface $model ) Gets belongsTo relations defined on a model public ResultsetInterface|bool getBelongsToRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets belongsTo related records from a model public BuilderInterface|null getBuilder() Returns the newly created Phalcon\Mvc\Model\Query\Builder or null public RelationInterface[]|array getHasMany( ModelInterface $model ) Gets hasMany relations defined on a model public ResultsetInterface|bool getHasManyRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets hasMany related records from a model public RelationInterface[]|array getHasManyToMany( ModelInterface $model ) Gets hasManyToMany relations defined on a model public RelationInterface[]|array getHasOne( ModelInterface $model ) Gets hasOne relations defined on a model public RelationInterface[] getHasOneAndHasMany( ModelInterface $model ) Gets hasOne relations defined on a model public ModelInterface|bool getHasOneRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null) Gets hasOne related records from a model public RelationInterface[]|array getHasOneThrough( ModelInterface $model ) Gets hasOneThrough relations defined on a model public ModelInterface|null getLastInitialized() Get last initialized model public QueryInterface getLastQuery() Returns the last query created or executed in the models manager public string|null getModelSchema( ModelInterface $model ) Returns the mapped schema for a model public string getModelSource( ModelInterface $model ) Returns the mapped source for a model public AdapterInterface getReadConnection( ModelInterface $model ) Returns the connection to read data related to a model public string getReadConnectionService( ModelInterface $model ) Returns the connection service name used to read data related to a model public RelationInterface|bool getRelationByAlias(string $modelName,string $alias) Returns a relation by its alias public getRelationRecords(RelationInterface $relation,ModelInterface $record,mixed $parameters = null,string $method = null) Helper method to query records based on a relation definition public RelationInterface[] getRelations( string $modelName ) Query all the relationships defined on a model public RelationInterface[]|bool getRelationsBetween(string $first,string $second) Query the relations between two models public getReusableRecords(string $modelName,string $key) Returns a reusable object from the internal list public AdapterInterface getWriteConnection( ModelInterface $model ) Returns the connection to write data related to a model public string getWriteConnectionService( ModelInterface $model ) Returns the connection service name used to write data related to a model public bool hasBelongsTo(string $modelName,string $modelRelation) Checks whether a model has a belongsTo relation with another model public bool hasHasMany(string $modelName,string $modelRelation) Checks whether a model has a hasMany relation with another model public bool hasHasManyToMany(string $modelName,string $modelRelation) Checks whether a model has a hasManyToMany relation with another model public bool hasHasOne(string $modelName,string $modelRelation) Checks whether a model has a hasOne relation with another model public bool hasHasOneThrough(string $modelName,string $modelRelation) Checks whether a model has a hasOneThrough relation with another model public initialize( ModelInterface $model ) Initializes a model in the model manager public bool isInitialized( string $className ) Check of a model is already initialized public bool isKeepingSnapshots( ModelInterface $model ) Checks if a model is keeping snapshots for the queried records public bool isUsingDynamicUpdate( ModelInterface $model ) Checks if a model is using dynamic update instead of all-field update public bool isVisibleModelProperty(ModelInterface $model,string $property) Check whether a model property is declared as public. public void keepSnapshots(ModelInterface $model,bool $keepSnapshots) Sets if a model must keep snapshots public ModelInterface load( string $modelName ) Loads a model throwing an exception if it does not exist public missingMethod(ModelInterface $model,string $eventName,mixed $data) Dispatch an event to the listeners and behaviors public notifyEvent(string $eventName,ModelInterface $model) Receives events generated in the models and dispatches them to an events-manager if available public void removeBehavior(ModelInterface $model,string $behaviorClass) Removes a behavior from a model public void setConnectionService(ModelInterface $model,string $connectionService) Sets both write and read connection service for a model public void setModelSchema(ModelInterface $model,string $schema) Sets the mapped schema for a model public void setModelSource(ModelInterface $model,string $source) Sets the mapped source for a model public void setReadConnectionService(ModelInterface $model,string $connectionService) Sets read connection service for a model public void setReusableRecords(string $modelName,string $key,mixed $records) Stores a reusable record in the internal list public setWriteConnectionService(ModelInterface $model,string $connectionService) Sets write connection service for a model public void useDynamicUpdate(ModelInterface $model,bool $dynamicUpdate) Sets if a model must use dynamic update instead of the all-field update public function addBelongsTo(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasMany(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasManyToMany(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasOne(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function addHasOneThrough(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
public function executeQuery(
string $phql,
mixed $placeholders = null,
mixed $types = null
): mixed;
public function getBelongsToRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
public function getHasManyRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
public function getHasOneRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ModelInterface|bool;
public function getRelationRecords(
RelationInterface $relation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
);
$metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
$attributes = $metaData->getAttributes(
new Robots()
);
print_r($attributes);
public CacheAdapterInterface|null getAdapter() Return the internal cache adapter public array getAttributes( ModelInterface $model ) Returns table attributes names (fields) public array getAutomaticCreateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the INSERT SQL generation public array getAutomaticUpdateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the UPDATE SQL generation public array getBindTypes( ModelInterface $model ) Returns attributes and their bind data types public array|null getColumnMap( ModelInterface $model ) Returns the column map if any public string|null getColumnMapUniqueKey( ModelInterface $model ) Returns a ColumnMap Unique key for meta-data is created using className public DiInterface getDI() Returns the DependencyInjector container public array getDataTypes( ModelInterface $model ) Returns attributes and their data types public array getDataTypesNumeric( ModelInterface $model ) Returns attributes which types are numerical public array getDefaultValues( ModelInterface $model ) Returns attributes (which have default values) and their default values public array getEmptyStringAttributes( ModelInterface $model ) Returns attributes allow empty strings public bool|string|null getIdentityField( ModelInterface $model ) Returns the name of identity field (if one is present) public string|null getMetaDataUniqueKey( ModelInterface $model ) Returns a MetaData Unique key for meta-data is created using className public string|null getModelUUID(ModelInterface $model,array $row) Returns the model UniqueID based on model and array row primary key(s) value(s) public array getNonPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are not part of the primary key public array getNotNullAttributes( ModelInterface $model ) Returns an array of not null attributes public array getPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are part of the primary key public array|null getReverseColumnMap( ModelInterface $model ) Returns the reverse column map if any public StrategyInterface getStrategy() Return the strategy to obtain the meta-data public bool hasAttribute(ModelInterface $model,string $attribute) Check if a model has certain attribute public bool isEmpty() Checks if the internal meta-data container is empty public bool modelEquals(ModelInterface $first,ModelInterface $other) Compares if two models are the same in memory public array|null read( mixed $key ) Reads metadata from the adapter public array|null readColumnMap( ModelInterface $model ) Reads the ordered/reversed column map for certain model public array|null readColumnMapIndex(ModelInterface $model,int $index) Reads column-map information for certain model using a MODEL_* constant public array|null readMetaData( ModelInterface $model ) Reads the complete meta-data for certain model public array|string|null readMetaDataIndex(ModelInterface $model,int $index) Reads meta-data for certain model public void reset() Resets internal meta-data in order to regenerate it public void setAutomaticCreateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the INSERT SQL generation public void setAutomaticUpdateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the UPDATE SQL generation public void setDI( DiInterface $container ) Sets the DependencyInjector container public void setEmptyStringAttributes(ModelInterface $model,array $attributes) Set the attributes that allow empty string values public void setStrategy( StrategyInterface $strategy ) Set the meta-data extraction strategy public void write(string $key,array $data) Writes the metadata to adapter public void writeMetaDataIndex(ModelInterface $model,int $index,mixed $data) Writes meta-data for certain model using a MODEL_* constant protected mixed getArrVal(array $collection,mixed $index,mixed $defaultValue = null) @todo Remove this when we get traits protected initialize(ModelInterface $model,mixed $key,mixed $table,mixed $schema) Initialize old behaviour for compatability protected bool initializeColumnMap(ModelInterface $model,mixed $key) Initialize ColumnMap for a certain table protected bool initializeMetaData(ModelInterface $model,mixed $key) Initialize the metadata for certain table int MODELS_ATTRIBUTES = 0 int MODELS_AUTOMATIC_DEFAULT_INSERT = 10 int MODELS_AUTOMATIC_DEFAULT_UPDATE = 11 int MODELS_COLUMN_MAP = 0 int MODELS_DATA_TYPES = 4 int MODELS_DATA_TYPES_BIND = 9 int MODELS_DATA_TYPES_NUMERIC = 5 int MODELS_DATE_AT = 6 int MODELS_DATE_IN = 7 int MODELS_DEFAULT_VALUES = 12 int MODELS_EMPTY_STRING_VALUES = 13 int MODELS_IDENTITY_COLUMN = 8 int MODELS_NON_PRIMARY_KEY = 2 int MODELS_NOT_NULL = 3 int MODELS_PRIMARY_KEY = 1 int MODELS_REVERSE_COLUMN_MAP = 1 protected CacheAdapterInterface|null $adapter = null protected array $columnMap = [] protected DiInterface|null $container = null protected array $metaData = [] protected array $pendingMetaDataWrites = [] Holds metadata index writes that arrived before the model's metadata was properly initialized (e.g. skipAttributes() called in a parent model's initialize() while the child's source had not yet been set). Applied inside initializeMetaData() after the real schema is loaded. protected StrategyInterface|null $strategy = null print_r(
$metaData->writeColumnMapIndex(
new Robots(),
MetaData::MODELS_REVERSE_COLUMN_MAP,
[
"leName" => "name",
]
)
);
final protected function initialize(
ModelInterface $model,
mixed $key,
mixed $table,
mixed $schema
);
public array getAttributes( ModelInterface $model ) Returns table attributes names (fields) public array getAutomaticCreateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the INSERT SQL generation public array getAutomaticUpdateAttributes( ModelInterface $model ) Returns attributes that must be ignored from the UPDATE SQL generation public array getBindTypes( ModelInterface $model ) Returns attributes and their bind data types public array|null getColumnMap( ModelInterface $model ) Returns the column map if any public array getDataTypes( ModelInterface $model ) Returns attributes and their data types public array getDataTypesNumeric( ModelInterface $model ) Returns attributes which types are numerical public array getDefaultValues( ModelInterface $model ) Returns attributes (which have default values) and their default values public array getEmptyStringAttributes( ModelInterface $model ) Returns attributes allow empty strings public bool|string|null getIdentityField( ModelInterface $model ) Returns the name of identity field (if one is present) public array getNonPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are not part of the primary key public array getNotNullAttributes( ModelInterface $model ) Returns an array of not null attributes public array getPrimaryKeyAttributes( ModelInterface $model ) Returns an array of fields which are part of the primary key public array|null getReverseColumnMap( ModelInterface $model ) Returns the reverse column map if any public StrategyInterface getStrategy() Return the strategy to obtain the meta-data public bool hasAttribute(ModelInterface $model,string $attribute) Check if a model has certain attribute public bool isEmpty() Checks if the internal meta-data container is empty public array|null read( string $key ) Reads meta-data from the adapter public array|null readColumnMap( ModelInterface $model ) Reads the ordered/reversed column map for certain model public array|null readColumnMapIndex(ModelInterface $model,int $index) Reads column-map information for certain model using a MODEL_* constant public array|null readMetaData( ModelInterface $model ) Reads meta-data for certain model public array|string|null readMetaDataIndex(ModelInterface $model,int $index) Reads meta-data for certain model using a MODEL_* constant public reset() Resets internal meta-data in order to regenerate it public setAutomaticCreateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the INSERT SQL generation public setAutomaticUpdateAttributes(ModelInterface $model,array $attributes) Set the attributes that must be ignored from the UPDATE SQL generation public void setEmptyStringAttributes(ModelInterface $model,array $attributes) Set the attributes that allow empty string values public setStrategy( StrategyInterface $strategy ) Set the meta-data extraction strategy public void write(string $key,array $data) Writes meta-data to the adapter public writeMetaDataIndex(ModelInterface $model,int $index,mixed $data) Writes meta-data for certain model using a MODEL_* constant $metaData = new \Phalcon\Mvc\Model\MetaData\Apcu(
[
"prefix" => "my-app-id",
"lifetime" => 86400,
]
);
public __construct(AdapterFactory $factory,array $options = []) Phalcon\Mvc\Model\MetaData\Libmemcached constructor public void reset() Flush Memcache data and resets internal meta-data in order to regenerate it public array|null read( mixed $key ) Reads the meta-data from temporal memory public void write(mixed $key,array $data) Writes the meta-data to temporal memory use Phalcon\Mvc\Model\MetaData\Redis;
$metaData = new Redis(
[
"host" => "127.0.0.1",
"port" => 6379,
"persistent" => 0,
"lifetime" => 172800,
"index" => 2,
]
);
public __construct(AdapterFactory $factory,array $options = []) Phalcon\Mvc\Model\MetaData\Redis constructor public void reset() Flush Redis data and resets internal meta-data in order to regenerate it public array getColumnMaps(ModelInterface $model,DiInterface $container) Read the model's column map, this can't be inferred public array getMetaData(ModelInterface $model,DiInterface $container) The meta-data is obtained by reading the column descriptions from the database information schema public array getColumnMaps(ModelInterface $model,DiInterface $container) Read the model's column map, this can't be inferred public array getMetaData(ModelInterface $model,DiInterface $container) The meta-data is obtained by reading the column descriptions from the database information schema public array getColumnMaps(ModelInterface $model,DiInterface $container) Read the model's column map, this can't be inferred public array getMetaData(ModelInterface $model,DiInterface $container) The meta-data is obtained by reading the column descriptions from the database information schema public __construct( array $options = [] ) Phalcon\Mvc\Model\MetaData\Files constructor public array|null read( mixed $key ) Reads meta-data from files public void write(mixed $key,array $data) Writes the meta-data to files protected string $metaDataDir = "./" $phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b
WHERE b.name = :name: ORDER BY c.name";
$result = $manager->executeQuery(
$phql,
[
"name" => "Lamborghini",
]
);
foreach ($result as $row) {
echo "Name: ", $row->cars->name, "\n";
echo "Price: ", $row->cars->price, "\n";
echo "Taxes: ", $row->taxes, "\n";
}
// with transaction
use Phalcon\Mvc\Model\Query;
use Phalcon\Mvc\Model\Transaction;
// $di needs to have the service "db" registered for this to work
$di = Phalcon\Di\FactoryDefault::getDefault();
$phql = 'SELECT * FROM robot';
$myTransaction = new Transaction($di);
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->type = "mechanical";
$newRobot->name = "Astro Boy";
$newRobot->year = 1952;
$newRobot->save();
$queryWithTransaction = new Query($phql, $di);
$queryWithTransaction->setTransaction($myTransaction);
$resultWithEntries = $queryWithTransaction->execute();
$queryWithOutTransaction = new Query($phql, $di);
$resultWithOutEntries = $queryWithTransaction->execute();
public __construct(string $phql = null,DiInterface $container = null,array $options = []) Phalcon\Mvc\Model\Query constructor public QueryInterface cache( array $cacheOptions ) Sets the cache parameters of the query public void clean() Destroys the internal PHQL cache public execute(array $bindParams = [],array $bindTypes = []) Executes a parsed PHQL statement public array getBindParams() Returns default bind params public array getBindTypes() Returns default bind types public AdapterInterface getCache() Returns the current cache backend instance public array getCacheOptions() Returns the current cache options public DiInterface getDI() Returns the dependency injection container public array getIntermediate() Returns the intermediate representation of the PHQL statement public ModelInterface getSingleResult(array $bindParams = [],array $bindTypes = []) Executes the query returning the first result public array getSql() Returns an associative array with the SQL to be generated by the internal PHQL, public TransactionInterface|null getTransaction() public int getType() Gets the type of PHQL statement executed public bool getUniqueRow() Check if the query is programmed to get only the first row in the public array parse() Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang public QueryInterface setBindParams(array $bindParams,bool $merge = false) Set default bind parameters public QueryInterface setBindTypes(array $bindTypes,bool $merge = false) Set default bind parameters public void setDI( DiInterface $container ) Sets the dependency injection container public QueryInterface setIntermediate( array $intermediate ) Allows to set the IR to be executed public QueryInterface setSharedLock( bool $sharedLock = false ) Set SHARED LOCK clause public QueryInterface setTransaction( TransactionInterface $transaction ) allows to wrap a transaction around all queries public QueryInterface setType( int $type ) Sets the type of PHQL statement to be executed public QueryInterface setUniqueRow( bool $uniqueRow ) Tells to the query if only the first row in the resultset must be protected StatusInterface executeDelete(array $intermediate,array $bindParams,array $bindTypes) Executes the DELETE intermediate representation producing a protected StatusInterface executeInsert(array $intermediate,array $bindParams,array $bindTypes) Executes the INSERT intermediate representation producing a protected ResultsetInterface|array executeSelect(array $intermediate,array $bindParams,array $bindTypes,bool $simulate = false) Executes the SELECT intermediate representation producing a protected StatusInterface executeUpdate(array $intermediate,array $bindParams,array $bindTypes) Executes the UPDATE intermediate representation producing a protected array getCallArgument( array $argument ) Resolves an expression in a single call argument protected array getCaseExpression( array $expr ) Resolves an expression in a single call argument protected array getExpression(array $expr,bool $quoting = true) Resolves an expression from its intermediate code into an array protected array getFunctionCall( array $expr ) Resolves an expression in a single call argument protected array getGroupClause( array $group ) Returns a processed group clause for a SELECT statement protected array getJoin(ManagerInterface $manager,array $join) Resolves a JOIN clause checking if the associated models exist protected string getJoinType( array $join ) Resolves a JOIN type protected array getJoins( array $select ) Processes the JOINs in the query returning an internal representation for protected array getLimitClause( array $limitClause ) Returns a processed limit clause for a SELECT statement protected array getMultiJoin(string $joinType,mixed $joinSource,string $modelAlias,string $joinAlias,RelationInterface $relation) Resolves joins involving many-to-many relations protected array getOrderClause( mixed $order ) Returns a processed order clause for a SELECT statement protected array getQualified( array $expr ) Replaces the model's name to its source name in a qualified-name protected AdapterInterface getReadConnection(ModelInterface $model,array $intermediate = null,array $bindParams = [],array $bindTypes = []) Gets the read connection from the model if there is no transaction set protected ResultsetInterface getRelatedRecords(ModelInterface $model,array $intermediate,array $bindParams,array $bindTypes) Query the records on which the UPDATE/DELETE operation will be done protected array getSelectColumn( array $column ) Resolves a column from its intermediate representation into an array protected array getSingleJoin(string $joinType,mixed $joinSource,string $modelAlias,string $joinAlias,RelationInterface $relation) Resolves joins involving has-one/belongs-to/has-many relations protected getTable(ManagerInterface $manager,array $qualifiedName) Resolves a table in a SELECT statement checking if the model exists protected AdapterInterface getWriteConnection(ModelInterface $model,array $intermediate = null,array $bindParams = [],array $bindTypes = []) Gets the write connection from the model if there is no transaction protected array prepareDelete() Analyzes a DELETE intermediate code and produces an array to be executed protected array prepareInsert() Analyzes an INSERT intermediate code and produces an array to be executed protected array prepareSelect(mixed $ast = null,bool $merge = false) Analyzes a SELECT intermediate code and produces an array to be executed later protected array prepareUpdate() Analyzes an UPDATE intermediate code and produces an array to be executed protected array refreshSchemasInIntermediate( array $irPhql ) Refreshes the schema/source of every model referenced in a cached int TYPE_DELETE = 303 int TYPE_INSERT = 306 int TYPE_SELECT = 309 int TYPE_UPDATE = 300 protected array $ast protected array $bindParams = [] protected array $bindTypes = [] protected mixed|null $cache = null protected array|null $cacheOptions protected DiInterface|null $container = null protected bool $enableImplicitJoins protected array $intermediate protected array|null $internalPhqlCache protected \Phalcon\Mvc\Model\ManagerInterface|null $manager = null protected \Phalcon\Mvc\Model\MetaDataInterface|null $metaData = null protected array $models = [] protected array $modelsInstances = [] protected int $nestingLevel = -1 protected string|null $phql = null protected bool $sharedLock = false protected array $sqlAliases = [] protected array $sqlAliasesModels = [] protected array $sqlAliasesModelsInstances = [] protected array $sqlColumnAliases = [] protected array $sqlModelsAliases = [] protected TransactionInterface|null $transaction = null TransactionInterface so that the query can wrap a transaction around batch updates and intermediate selects within the transaction. however if a model got a transaction set inside it will use the local transaction instead of this one protected int|null $type protected bool $uniqueRow = false public function __construct(
string $phql = null,
DiInterface $container = null,
array $options = []
);
[
'sql' => 'SELECT * FROM parts WHERE robot = :robot',
'bind' => ['robot' => 123],
'bindTypes => ['robot' => 1] // 1 corresponds to int
]
final protected function executeDelete(
array $intermediate,
array $bindParams,
array $bindTypes
): StatusInterface;
final protected function executeInsert(
array $intermediate,
array $bindParams,
array $bindTypes
): StatusInterface;
final protected function executeSelect(
array $intermediate,
array $bindParams,
array $bindTypes,
bool $simulate = false
): ResultsetInterface|array;
final protected function executeUpdate(
array $intermediate,
array $bindParams,
array $bindTypes
): StatusInterface;
final protected function getMultiJoin(
string $joinType,
mixed $joinSource,
string $modelAlias,
string $joinAlias,
RelationInterface $relation
): array;
protected function getReadConnection(
ModelInterface $model,
array $intermediate = null,
array $bindParams = [],
array $bindTypes = []
): AdapterInterface;
final protected function getRelatedRecords(
ModelInterface $model,
array $intermediate,
array $bindParams,
array $bindTypes
): ResultsetInterface;
final protected function getSingleJoin(
string $joinType,
mixed $joinSource,
string $modelAlias,
string $joinAlias,
RelationInterface $relation
): array;
protected function getWriteConnection(
ModelInterface $model,
array $intermediate = null,
array $bindParams = [],
array $bindTypes = []
): AdapterInterface;
public QueryInterface cache( array $cacheOptions ) Sets the cache parameters of the query public execute(array $bindParams = [],array $bindTypes = []) Executes a parsed PHQL statement public array getBindParams() Returns default bind params public array getBindTypes() Returns default bind types public array getCacheOptions() Returns the current cache options public ModelInterface getSingleResult(array $bindParams = [],array $bindTypes = []) Executes the query returning the first result public array getSql() Returns the SQL to be generated by the internal PHQL (only works in SELECT statements) public bool getUniqueRow() Check if the query is programmed to get only the first row in the resultset public array parse() Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another public QueryInterface setBindParams(array $bindParams,bool $merge = false) Set default bind parameters public QueryInterface setBindTypes(array $bindTypes,bool $merge = false) Set default bind parameters public QueryInterface setSharedLock( bool $sharedLock = false ) Set SHARED LOCK clause public QueryInterface setUniqueRow( bool $uniqueRow ) Tells to the query if only the first row in the resultset must be returned $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);
public __construct(mixed $params = null,DiInterface $container = null) Phalcon\Mvc\Model\Query\Builder constructor public BuilderInterface addFrom(string $model,string $alias = null) Add a model to take part of the query public BuilderInterface andHaving(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current HAVING conditions clause using a AND operator public BuilderInterface andWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current WHERE conditions using a AND operator public string autoescape( string $identifier ) Automatically escapes identifiers but only if they need to be escaped. public BuilderInterface betweenHaving(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a BETWEEN condition to the current HAVING conditions clause public BuilderInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a BETWEEN condition to the current WHERE conditions public BuilderInterface columns( mixed $columns ) Sets the columns to be queried. The columns can be either a string or public BuilderInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public BuilderInterface forUpdate( bool $forUpdate ) Sets a FOR UPDATE clause public BuilderInterface from( mixed $models ) Sets the models who makes part of the query public array getBindParams() Returns default bind params public array getBindTypes() Returns default bind types public getColumns() Return the columns to be queried public DiInterface getDI() Returns the DependencyInjector container public bool getDistinct() Returns SELECT DISTINCT / SELECT ALL flag public getFrom() Return the models who makes part of the query public array getGroupBy() Returns the GROUP BY clause public string|null getHaving() Return the current having clause public array getJoins() Return join parts of the query public getLimit() Returns the current LIMIT clause public string|array|null getModels() Returns the models involved in the query public int getOffset() Returns the current OFFSET clause public getOrderBy() Returns the set ORDER BY clause public string getPhql() Returns a PHQL statement built based on the builder parameters public QueryInterface getQuery() Returns the query built public getWhere() Return the conditions for the query public BuilderInterface groupBy( mixed $group ) Sets a GROUP BY clause public BuilderInterface having(string $conditions,array $bindParams = [],array $bindTypes = []) Sets the HAVING condition clause public BuilderInterface inHaving(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends an IN condition to the current HAVING conditions clause public BuilderInterface inWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends an IN condition to the current WHERE conditions public BuilderInterface innerJoin(string $model,string $conditions = null,string $alias = null) Adds an INNER join to the query public BuilderInterface join(string $model,string $conditions = null,string $alias = null,string $type = null) Adds an :type: join (by default type - INNER) to the query public BuilderInterface leftJoin(string $model,string $conditions = null,string $alias = null) Adds a LEFT join to the query public BuilderInterface limit(int $limit,mixed $offset = null) Sets a LIMIT clause, optionally an offset clause public BuilderInterface notBetweenHaving(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT BETWEEN condition to the current HAVING conditions clause public BuilderInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT BETWEEN condition to the current WHERE conditions public BuilderInterface notInHaving(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT IN condition to the current HAVING conditions clause public BuilderInterface notInWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT IN condition to the current WHERE conditions public BuilderInterface offset( int $offset ) Sets an OFFSET clause public BuilderInterface orHaving(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current HAVING conditions clause using an OR operator public BuilderInterface orWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current conditions using an OR operator public BuilderInterface orderBy( mixed $orderBy ) Sets an ORDER BY condition clause public BuilderInterface rightJoin(string $model,string $conditions = null,string $alias = null) Adds a RIGHT join to the query public BuilderInterface setBindParams(array $bindParams,bool $merge = false) Set default bind parameters public BuilderInterface setBindTypes(array $bindTypes,bool $merge = false) Set default bind types public void setDI( DiInterface $container ) Sets the DependencyInjector container public BuilderInterface where(string $conditions,array $bindParams = [],array $bindTypes = []) Sets the query WHERE conditions protected BuilderInterface conditionBetween(string $clause,string $operator,string $expr,mixed $minimum,mixed $maximum) Appends a BETWEEN condition protected BuilderInterface conditionIn(string $clause,string $operator,string $expr,array $values) Appends an IN condition protected BuilderInterface conditionNotBetween(string $clause,string $operator,string $expr,mixed $minimum,mixed $maximum) Appends a NOT BETWEEN condition protected BuilderInterface conditionNotIn(string $clause,string $operator,string $expr,array $values) Appends a NOT IN condition protected array $bindParams = [] protected array $bindTypes = [] protected array|string|null $columns = null protected array|string|null $conditions = null protected DiInterface|null $container protected mixed $distinct = null protected bool $forUpdate = false protected array $group = [] protected string|null $having = null protected int $hiddenParamNumber = 0 protected array $joins = [] protected array|string $limit protected array|string $models protected int $offset = 0 protected array|string $order protected bool $sharedLock = false // Load data from models Robots
$builder->addFrom(
Robots::class
);
// Load data from model 'Robots' using 'r' as alias in PHQL
$builder->addFrom(
Robots::class,
"r"
);
public function andHaving(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
$builder->andHaving("SUM(Robots.price) > 0");
$builder->andHaving(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function andWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
$builder->andWhere("name = 'Peter'");
$builder->andWhere(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
public function betweenHaving(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function betweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
<?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",
]
);
$builder->from(
Robots::class
);
$builder->from(
[
Robots::class,
RobotsParts::class,
]
);
$builder->from(
[
"r" => Robots::class,
"rp" => RobotsParts::class,
]
);
public function having(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
$builder->having("SUM(Robots.price) > 0");
$builder->having(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function inHaving(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function inWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function innerJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
// Inner Join model 'Robots' with automatic conditions and alias
$builder->innerJoin(
Robots::class
);
// Inner Join model 'Robots' specifying conditions
$builder->innerJoin(
Robots::class,
"Robots.id = RobotsParts.robots_id"
);
// Inner Join model 'Robots' specifying conditions and alias
$builder->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
public function join(
string $model,
string $conditions = null,
string $alias = null,
string $type = null
): BuilderInterface;
// Inner Join model 'Robots' with automatic conditions and alias
$builder->join(
Robots::class
);
// Inner Join model 'Robots' specifying conditions
$builder->join(
Robots::class,
"Robots.id = RobotsParts.robots_id"
);
// Inner Join model 'Robots' specifying conditions and alias
$builder->join(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
// Left Join model 'Robots' specifying conditions, alias and type of join
$builder->join(
Robots::class,
"r.id = RobotsParts.robots_id",
"r",
"LEFT"
);
public function leftJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
public function notBetweenHaving(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function notBetweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function notInHaving(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function notInWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function orHaving(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
$builder->orHaving("SUM(Robots.price) > 0");
$builder->orHaving(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function orWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
$builder->orWhere("name = 'Peter'");
$builder->orWhere(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
$builder->orderBy("Robots.name");
$builder->orderBy(["1", "Robots.name"]);
$builder->orderBy(["Robots.name DESC"]);
public function rightJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
public function where(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
$builder->where(100);
$builder->where("name = 'Peter'");
$builder->where(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
protected function conditionBetween(
string $clause,
string $operator,
string $expr,
mixed $minimum,
mixed $maximum
): BuilderInterface;
protected function conditionIn(
string $clause,
string $operator,
string $expr,
array $values
): BuilderInterface;
protected function conditionNotBetween(
string $clause,
string $operator,
string $expr,
mixed $minimum,
mixed $maximum
): BuilderInterface;
protected function conditionNotIn(
string $clause,
string $operator,
string $expr,
array $values
): BuilderInterface;
public BuilderInterface addFrom(string $model,string $alias = null) Add a model to take part of the query public BuilderInterface andWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current conditions using a AND operator public BuilderInterface betweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a BETWEEN condition to the current conditions public BuilderInterface columns( mixed $columns ) Sets the columns to be queried. The columns can be either a string or public BuilderInterface distinct( mixed $distinct ) Sets SELECT DISTINCT / SELECT ALL flag public BuilderInterface forUpdate( bool $forUpdate ) Sets a FOR UPDATE clause public BuilderInterface from( mixed $models ) Sets the models who makes part of the query public array getBindParams() Returns default bind params public array getBindTypes() Returns default bind types public getColumns() Return the columns to be queried public bool getDistinct() Returns SELECT DISTINCT / SELECT ALL flag public getFrom() Return the models who makes part of the query public array getGroupBy() Returns the GROUP BY clause public string|null getHaving() Returns the HAVING condition clause public array getJoins() Return join parts of the query public getLimit() Returns the current LIMIT clause public string|array|null getModels() Returns the models involved in the query public int getOffset() Returns the current OFFSET clause public getOrderBy() Return the set ORDER BY clause public string getPhql() Returns a PHQL statement built based on the builder parameters public QueryInterface getQuery() Returns the query built public getWhere() Return the conditions for the query public BuilderInterface groupBy( mixed $group ) Sets a GROUP BY clause public BuilderInterface having(string $conditions,array $bindParams = [],array $bindTypes = []) Sets a HAVING condition clause public BuilderInterface inWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends an IN condition to the current conditions public BuilderInterface innerJoin(string $model,string $conditions = null,string $alias = null) Adds an INNER join to the query public BuilderInterface join(string $model,string $conditions = null,string $alias = null) Adds an :type: join (by default type - INNER) to the query public BuilderInterface leftJoin(string $model,string $conditions = null,string $alias = null) Adds a LEFT join to the query public BuilderInterface limit(int $limit,mixed $offset = null) Sets a LIMIT clause public BuilderInterface notBetweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT BETWEEN condition to the current conditions public BuilderInterface notInWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND) Appends a NOT IN condition to the current conditions public BuilderInterface offset( int $offset ) Sets an OFFSET clause public BuilderInterface orWhere(string $conditions,array $bindParams = [],array $bindTypes = []) Appends a condition to the current conditions using an OR operator public BuilderInterface orderBy( mixed $orderBy ) Sets an ORDER BY condition clause public BuilderInterface rightJoin(string $model,string $conditions = null,string $alias = null) Adds a RIGHT join to the query public BuilderInterface setBindParams(array $bindParams,bool $merge = false) Set default bind parameters public BuilderInterface setBindTypes(array $bindTypes,bool $merge = false) Set default bind types public BuilderInterface where(string $conditions,array $bindParams = [],array $bindTypes = []) Sets conditions for the query string OPERATOR_AND = "and" string OPERATOR_OR = "or" public function andWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
public function betweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
<?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",
]
);
public function having(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
public function inWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function innerJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
public function join(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
public function leftJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
public function notBetweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function notInWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
public function orWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
public function rightJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
public function where(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
use Phalcon\Mvc\Model\Query\Lang;
$intermediate = Lang::parsePHQL(
"SELECT r.* FROM Robots r LIMIT 10"
);
$phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";
$status = $app->modelsManager->executeQuery(
$phql,
[
"id" => 100,
"name" => "Astroy Boy",
"type" => "mechanical",
"year" => 1959,
]
);
// Check if the update was successful
if ($status->success()) {
echo "OK";
}
public __construct(bool $success,ModelInterface $model = null) Phalcon\Mvc\Model\Query\Status public MessageInterface[] getMessages() Returns the messages produced because of a failed operation public ModelInterface|null getModel() Returns the model that executed the action public bool success() Allows to check if the executed operation was successful protected ModelInterface|null $model protected bool $success public MessageInterface[] getMessages() Returns the messages produced by an operation failed public ModelInterface|null getModel() Returns the model which executed the action public bool success() Allows to check if the executed operation was successful public __construct(int $type,string $referencedModel,mixed $fields,mixed $referencedFields,array $options = []) Phalcon\Mvc\Model\Relation constructor public getFields() Returns the fields public getForeignKey() Returns the foreign key configuration public getIntermediateFields() Gets the intermediate fields for has-*-through relations public string getIntermediateModel() Gets the intermediate model for has-*-through relations public getIntermediateReferencedFields() Gets the intermediate referenced fields for has-*-through relations public getOption( string $name ) Returns an option by the specified name public array getOptions() Returns the options public getParams() Returns parameters that must be always used when the related records are obtained public getReferencedFields() Returns the referenced fields public string getReferencedModel() Returns the referenced model public int getType() Returns the relation type public bool isForeignKey() Check whether the relation act as a foreign key public bool isReusable() Check if records returned by getting belongs-to/has-many are implicitly cached during the current request public bool isThrough() Check whether the relation is a 'many-to-many' relation or not public setIntermediateRelation(mixed $intermediateFields,string $intermediateModel,mixed $intermediateReferencedFields) Sets the intermediate model data for has-*-through relations int ACTION_CASCADE = 2 int ACTION_RESTRICT = 1 int BELONGS_TO = 0 int HAS_MANY = 2 int HAS_MANY_THROUGH = 4 int HAS_ONE = 1 int HAS_ONE_THROUGH = 3 int NO_ACTION = 0 protected array|string $fields protected array|string $intermediateFields protected string|null $intermediateModel = null protected array|string $intermediateReferencedFields protected array $options = [] protected array|string $referencedFields protected string $referencedModel protected int $type public function __construct(
int $type,
string $referencedModel,
mixed $fields,
mixed $referencedFields,
array $options = []
);
public function setIntermediateRelation(
mixed $intermediateFields,
string $intermediateModel,
mixed $intermediateReferencedFields
);
public getFields() Returns the fields public getForeignKey() Returns the foreign key configuration public getIntermediateFields() Gets the intermediate fields for has-*-through relations public string getIntermediateModel() Gets the intermediate model for has-*-through relations public getIntermediateReferencedFields() Gets the intermediate referenced fields for has-*-through relations public getOption( string $name ) Returns an option by the specified name public array getOptions() Returns the options public getParams() Returns parameters that must be always used when the related records are obtained public getReferencedFields() Returns the referenced fields public string getReferencedModel() Returns the referenced model public int getType() Returns the relations type public bool isForeignKey() Check whether the relation act as a foreign key public bool isReusable() Check if records returned by getting belongs-to/has-many are implicitly cached during the current request public bool isThrough() Check whether the relation is a 'many-to-many' relation or not public setIntermediateRelation(mixed $intermediateFields,string $intermediateModel,mixed $intermediateReferencedFields) Sets the intermediate model data for has-*-through relations public function setIntermediateRelation(
mixed $intermediateFields,
string $intermediateModel,
mixed $intermediateReferencedFields
);
// Using a standard foreach
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($robots as robot) {
echo robot->name, "\n";
}
// Using a while
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
$robots->rewind();
while ($robots->valid()) {
$robot = $robots->current();
echo $robot->name, "\n";
$robots->next();
}
public __construct(mixed $result,mixed $cache = null) Phalcon\Mvc\Model\Resultset constructor public int count() Counts how many rows are in the resultset public bool delete( Closure $conditionCallback = null ) Deletes every record in the resultset public ModelInterface[] filter( callable $filter ) Filters a resultset returning only those the developer requires public CacheInterface|null getCache() Returns the associated cache for the resultset public mixed|null getFirst() Get first row in the resultset public int getHydrateMode() Returns the current hydration mode public ModelInterface|null getLast() Get last row in the resultset public MessageInterface[] getMessages() Returns the error messages produced by a batch operation public mixed getResult() public int getType() Returns the internal type of data retrieval that the resultset is using public bool isFresh() Tell if the resultset if fresh or an old one cached public array jsonSerialize() Returns serialised model objects as array for json_encode. public int|null key() Gets pointer number of active row in the resultset public void next() Moves cursor to next row in the resultset public bool offsetExists( mixed $index ) Checks whether offset exists in the resultset public mixed offsetGet( mixed $index ) Gets row in a specific position of the resultset public void offsetSet(mixed $offset,mixed $value) Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface public void offsetUnset( mixed $offset ) Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface public bool refresh() public void rewind() Rewinds resultset to its beginning public void seek( mixed $position ) Changes the internal pointer to a specific position in the resultset. public ResultsetInterface setHydrateMode( int $hydrateMode ) Sets the hydration mode in the resultset public ResultsetInterface setIsFresh( bool $isFresh ) Set if the resultset is fresh or an old one cached public bool update(mixed $data,Closure $conditionCallback = null) Updates every record in the resultset public bool valid() Check whether internal resource has rows to fetch int HYDRATE_ARRAYS = 1 int HYDRATE_OBJECTS = 2 int HYDRATE_RECORDS = 0 int TYPE_RESULT_FULL = 0 int TYPE_RESULT_PARTIAL = 1 protected mixed|null $activeRow = null protected CacheInterface|null $cache = null protected int $count = 0 protected array $errorMessages = [] protected int $hydrateMode = 0 protected bool $isFresh = true protected int $pointer = 0 protected ResultInterface|bool $result Phalcon\Db\ResultInterface or false for empty resultset protected mixed|null $row = null protected array|null $rows = null $model = new Robots();
$manager = $model->getModelsManager();
// \Robots
$manager->createQuery('SELECT * FROM Robots')
->execute()
->getFirst();
// \Phalcon\Mvc\Model\Row
$manager->createQuery('SELECT r.id FROM Robots AS r')
->execute()
->getFirst();
// NULL
$manager->createQuery('SELECT r.id FROM Robots AS r WHERE r.name = "NON-EXISTENT"')
->execute()
->getFirst();
public bool delete( Closure $conditionCallback = null ) Deletes every record in the resultset public ModelInterface[] filter( callable $filter ) Filters a resultset returning only those the developer requires public mixed|null getCache() Returns the associated cache for the resultset public mixed|null getFirst() Get first row in the resultset public int getHydrateMode() Returns the current hydration mode public ModelInterface|null getLast() Get last row in the resultset public MessageInterface[] getMessages() Returns the error messages produced by a batch operation public int getType() Returns the internal type of data retrieval that the resultset is using public bool isFresh() Tell if the resultset if fresh or an old one cached public ResultsetInterface setHydrateMode( int $hydrateMode ) Sets the hydration mode in the resultset public ResultsetInterface setIsFresh( bool $isFresh ) Set if the resultset is fresh or an old one cached public array toArray() Returns a complete resultset as an array, if the resultset has a big number of rows public bool update(mixed $data,Closure $conditionCallback = null) Updates every record in the resultset public __construct(mixed $columnTypes,ResultInterface $result = null,mixed $cache = null) Phalcon\Mvc\Model\Resultset\Complex constructor public array __serialize() public void __unserialize( array $data ) public mixed current() Returns current row in the resultset public string serialize() Serializing a resultset will dump all related rows into a big array, public array toArray() Returns a complete resultset as an array, if the resultset has a big public void unserialize( mixed $data ) Unserializing a resultset will allow to only works on the rows present in the saved state protected array $columnTypes protected bool $disableHydration = false Unserialised result-set hydrated all rows already. unserialise() sets disableHydration to true public function __construct(
mixed $columnTypes,
ResultInterface $result = null,
mixed $cache = null
);
public __construct(mixed $columnMap,mixed $model,mixed $result,mixed $cache = null,bool $keepSnapshots = false) Phalcon\Mvc\Model\Resultset\Simple constructor public array __serialize() public void __unserialize( array $data ) public ModelInterface|Row|null current() Returns current row in the resultset public string serialize() Serializing a resultset will dump all related rows into a big array public array toArray( bool $renameColumns = true ) Returns a complete resultset as an array, if the resultset has a big public void unserialize( mixed $data ) Unserializing a resultset will allow to only works on the rows present in protected array|string $columnMap protected bool $keepSnapshots = false protected ModelInterface|Row $model public function __construct(
mixed $columnMap,
mixed $model,
mixed $result,
mixed $cache = null,
bool $keepSnapshots = false
);
public array jsonSerialize() Serializes the object for json_encode public bool offsetExists( mixed $index ) Checks whether offset exists in the row. Returns true when the property public mixed offsetGet( mixed $index ) Gets a record in a specific position of the row public void offsetSet(mixed $offset,mixed $value) Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface public void offsetUnset( mixed $offset ) Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface public readAttribute( string $attribute ) Reads an attribute value by its name public ModelInterface|bool setDirtyState( int $dirtyState ) Set the current object's state public array toArray() Returns the instance as an array representation public void writeAttribute(string $attribute,mixed $value) Writes an attribute value by its name use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$manager = new Manager();
$transaction = $manager->get();
$robot = new Robots();
$robot->setTransaction($transaction);
$robot->name = "WALL·E";
$robot->created_at = date("Y-m-d");
if ($robot->save() === false) {
$transaction->rollback("Can't save robot");
}
$robotPart = new RobotParts();
$robotPart->setTransaction($transaction);
$robotPart->type = "head";
if ($robotPart->save() === false) {
$transaction->rollback("Can't save robot part");
}
$transaction->commit();
} catch(Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
public __construct(DiInterface $container,bool $autoBegin = false,string $service = "db") Phalcon\Mvc\Model\Transaction constructor public bool begin() Starts the transaction public bool commit() Commits the transaction public AdapterInterface getConnection() Returns the connection related to transaction public array getMessages() Returns validations messages from last save try public bool isManaged() Checks whether transaction is managed by a transaction manager public bool isValid() Checks whether internal connection is under an active transaction public bool rollback(string $rollbackMessage = null,ModelInterface $rollbackRecord = null) Rollbacks the transaction public void setIsNewTransaction( bool $isNew ) Sets if is a reused transaction or new once public void setRollbackOnAbort( bool $rollbackOnAbort ) Sets flag to rollback on abort the HTTP connection public void setRollbackedRecord( ModelInterface $record ) Sets object which generates rollback action public void setTransactionManager( ManagerInterface $manager ) Sets transaction manager related to the transaction public TransactionInterface throwRollbackException( bool $status ) Enables throwing exception protected bool $activeTransaction = false protected AdapterInterface $connection protected bool $isNewTransaction = true protected ManagerInterface|null $manager = null protected array $messages = [] protected bool $rollbackOnAbort = false protected ModelInterface|null $rollbackRecord = null protected bool $rollbackThrowException = false public function __construct(
DiInterface $container,
bool $autoBegin = false,
string $service = "db"
);
public function rollback(
string $rollbackMessage = null,
ModelInterface $rollbackRecord = null
): bool;
public bool begin() Starts the transaction public bool commit() Commits the transaction public \Phalcon\Db\Adapter\AdapterInterface getConnection() Returns connection related to transaction public array getMessages() Returns validations messages from last save try public bool isManaged() Checks whether transaction is managed by a transaction manager public bool isValid() Checks whether internal connection is under an active transaction public bool rollback(string $rollbackMessage = null,ModelInterface $rollbackRecord = null) Rollbacks the transaction public void setIsNewTransaction( bool $isNew ) Sets if is a reused transaction or new once public void setRollbackOnAbort( bool $rollbackOnAbort ) Sets flag to rollback on abort the HTTP connection public void setRollbackedRecord( ModelInterface $record ) Sets object which generates rollback action public void setTransactionManager( ManagerInterface $manager ) Sets transaction manager related to the transaction public TransactionInterface throwRollbackException( bool $status ) Enables throwing exception public function rollback(
string $rollbackMessage = null,
ModelInterface $rollbackRecord = null
): bool;
public __construct(string $message,ModelInterface $record = null) Phalcon\Mvc\Model\Transaction\Failed constructor public ModelInterface|null getRecord() Returns validation record messages which stop the transaction public array|string getRecordMessages() Returns validation record messages which stop the transaction protected ModelInterface|null $record = null use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$transactionManager = new Manager();
$transaction = $transactionManager->get();
$robot = new Robots();
$robot->setTransaction($transaction);
$robot->name = "WALL·E";
$robot->created_at = date("Y-m-d");
if ($robot->save() === false) {
$transaction->rollback("Can't save robot");
}
$robotPart = new RobotParts();
$robotPart->setTransaction($transaction);
$robotPart->type = "head";
if ($robotPart->save() === false) {
$transaction->rollback("Can't save robot part");
}
$transaction->commit();
} catch (Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
public __construct( DiInterface $container = null ) Phalcon\Mvc\Model\Transaction\Manager constructor public void collectTransactions() Remove all the transactions from the manager public commit() Commits active transactions within the manager public TransactionInterface get( bool $autoBegin = true ) Returns a new \Phalcon\Mvc\Model\Transaction or an already created once public DiInterface getDI() Returns the dependency injection container public string getDbService() Returns the database service used to isolate the transaction public TransactionInterface getOrCreateTransaction( bool $autoBegin = true ) Create/Returns a new transaction or an existing one public bool getRollbackPendent() Check if the transaction manager is registering a shutdown function to public bool has() Checks whether the manager has an active transaction public void notifyCommit( TransactionInterface $transaction ) Notifies the manager about a committed transaction public void notifyRollback( TransactionInterface $transaction ) Notifies the manager about a rollbacked transaction public void rollback( bool $collect = true ) Rollbacks active transactions within the manager public void rollbackPendent() Rollbacks active transactions within the manager public void setDI( DiInterface $container ) Sets the dependency injection container public ManagerInterface setDbService( string $service ) Sets the database service used to run the isolated transactions public ManagerInterface setRollbackPendent( bool $rollbackPendent ) Set if the transaction manager must register a shutdown function to clean protected void collectTransaction( TransactionInterface $transaction ) Removes transactions from the TransactionManager protected DiInterface|null $container protected bool $initialized = false protected int $number = 0 protected bool $rollbackPendent = true protected string $service = "db" protected array $transactions = [] public void collectTransactions() Remove all the transactions from the manager public commit() Commits active transactions within the manager public TransactionInterface get( bool $autoBegin = true ) Returns a new \Phalcon\Mvc\Model\Transaction or an already created once public string getDbService() Returns the database service used to isolate the transaction public bool getRollbackPendent() Check if the transaction manager is registering a shutdown function to clean up pendent transactions public bool has() Checks whether manager has an active transaction public void notifyCommit( TransactionInterface $transaction ) Notifies the manager about a committed transaction public void notifyRollback( TransactionInterface $transaction ) Notifies the manager about a rollbacked transaction public void rollback( bool $collect = false ) Rollbacks active transactions within the manager public void rollbackPendent() Rollbacks active transactions within the manager public ManagerInterface setDbService( string $service ) Sets the database service used to run the isolated transactions public ManagerInterface setRollbackPendent( bool $rollbackPendent ) Set if the transaction manager must register a shutdown function to clean up pendent transactions public __construct(ModelInterface $model,array $validationMessages) Phalcon\Mvc\Model\ValidationFailed constructor public Message[] getMessages() Returns the complete group of messages produced in the validation public ModelInterface getModel() Returns the model that generated the messages protected ModelInterface $model protected array $validationMessages = [] public registerAutoloaders( DiInterface $container = null ) Registers an autoloader related to the module public registerServices( DiInterface $container ) Registers services related to the module 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();
public __construct( bool $defaultRoutes = true ) Phalcon\Mvc\Router constructor public RouteInterface add(string $pattern,mixed $paths = null,mixed $httpMethods = null,int $position = Router::POSITION_LAST) Adds a route to the router without any HTTP constraint public RouteInterface addConnect(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is CONNECT public RouteInterface addDelete(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is DELETE public RouteInterface addGet(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is GET public RouteInterface addHead(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is HEAD public RouteInterface addOptions(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Add a route to the router that only match if the HTTP method is OPTIONS public RouteInterface addPatch(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PATCH public RouteInterface addPost(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is POST public RouteInterface addPurge(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PURGE public RouteInterface addPut(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is PUT public RouteInterface addTrace(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST) Adds a route to the router that only match if the HTTP method is TRACE public static attach(RouteInterface $route,int $position = Router::POSITION_LAST) Attach Route object to the routes stack. public array buildDispatcherDump() Produces a pure-data array describing every piece of state needed public void clear() Removes all the pre-defined routes public void dumpDispatcher( string $path ) File-shaped helper around buildDispatcherDump(). Writes the dump as public string getActionName() Returns the processed action name public string getControllerName() Returns the processed controller name public array getDefaults() Returns an array of default parameters public ManagerInterface|null getEventsManager() Returns the internal event manager public array getKeyRouteIds() public array getKeyRouteNames() public RouteInterface|null getMatchedRoute() Returns the route that matches the handled URI public array getMatches() Returns the sub expressions in the regular expression matched public array getMethodRoutes() Returns the routes indexed by HTTP method. public string getModuleName() Returns the processed module name public string getNamespaceName() Returns the processed namespace name public array getParams() Returns the processed parameters public string getRewriteUri() Get rewrite info. This info is read from $_GET["_url"]. public RouteInterface|bool getRouteById( mixed $routeId ) Returns a route object by its id public RouteInterface|bool getRouteByName( string $name ) Returns a route object by its name public RouteInterface[] getRoutes() Returns all the routes defined in the router public void handle( string $uri ) Handles routing information received from the rewrite engine public bool isExactControllerName() Returns whether controller name should not be mangled public void loadDispatcher( string $path ) File-shaped helper around loadDispatcherFromArray(). Includes the public void loadDispatcherFromArray( array $dump ) Inverse of buildDispatcherDump(). Reconstructs every Route from the public static loadFromConfig( mixed $config ) Loads routes from an array or Phalcon\Config\Config instance. public static mount( GroupInterface $group ) Mounts a group of routes in the router public static notFound( mixed $paths ) Set a group of paths to be returned when none of the defined routes are public static removeExtraSlashes( bool $remove ) Set whether router must remove the extra slashes in the handled routes public static setDefaultAction( string $actionName ) Sets the default action name public static setDefaultController( string $controllerName ) Sets the default controller name public static setDefaultModule( string $moduleName ) Sets the name of the default module public static setDefaultNamespace( string $namespaceName ) Sets the name of the default namespace public static setDefaults( array $defaults ) Sets an array of default paths. If a route is missing a path the router public void setEventsManager( ManagerInterface $eventsManager ) Sets the events manager public static setKeyRouteIds( array $routeIds ) public static setKeyRouteNames( array $routeNames ) public static setUriSource( int $uriSource ) Sets the URI source. One of the URI_SOURCE_* constants public void useCache(CacheAdapterInterface $cache,string $key = "phalcon.router.dispatcher") Cache-instance convenience wrapper. On cache hit, restores the public bool wasMatched() Checks if the router matches any of the defined routes protected void addRouteFromConfig( array $routeData ) Adds a single route from a config array entry. Used by loadFromConfig. protected string extractRealUri( string $uri ) protected void mountGroupFromConfig( array $groupData ) Builds a Group from a config entry and mounts it. Used by loadFromConfig. protected void rebuildMethodIndex() int POSITION_FIRST = 0 int POSITION_LAST = 1 int REGEX_CHUNK_SIZE = 10 Number of alternatives per combined-regex chunk. Empirically derived (FastRoute uses ~10) - keeps each chunk below PCRE's optimizer cliff. int URI_SOURCE_GET_URL = 0 int URI_SOURCE_SERVER_REQUEST_URI = 1 protected string $action = "" protected array $candidatesByMethod = [] Pre-merged per-method candidate buckets in attach order. For each HTTP method seen on any registered route, the bucket contains the method-specific routes followed by the "*" (no-constraint) routes. The "*" key itself holds only the no-constraint routes - used when the request method has no specific bucket. Built in rebuildMethodIndex(); consumed by handle() in reverse. protected array $combinedRegexByMethod = [] Combined PCRE pattern per method bucket (chunked list of strings). Each chunk uses (?|...) branch reset and (*:N) mark labels. Built only when the bucket meets gating: no hostname routes; standard pattern shape. protected array $combinedRegexDisabled = [] Boolean per method bucket: true when the combined regex cannot be built (hostname route present, exotic pattern shape, etc.). protected array $combinedRegexMarkMap = [] Map from MARK label back to the route index in candidatesByMethod[method]. One per chunk. combinedRegexMarkMap[method][chunkIdx][markLabel] = routeIdx protected string $controller = "" protected string $defaultAction = "" protected string $defaultController = "" protected string $defaultModule = "" protected string $defaultNamespace = "" protected array $defaultParams = [] protected ManagerInterface|null $eventsManager protected array $hostnameByMethod = [] Per-method buckets of routes with hostname constraints, grouped by raw hostname string. Routes are referenced by their index into candidatesByMethod[method]. Built in rebuildMethodIndex(). Shape: hostnameByMethod[method][hostname] = list of route indices. protected array $hostnameLessByMethod = [] Per-method indices of routes without a hostname constraint, in attach order. Shape: hostnameLessByMethod[method] = list of route indices into candidatesByMethod[method]. protected array $keyRouteIds = [] protected array $keyRouteNames = [] protected RouteInterface|null $matchedRoute = null protected array $matches = [] protected array $methodRoutes = [] protected bool $methodRoutesDirty = true protected string $module = "" protected string $namespaceName = "" protected array|string|null $notFoundPaths = null protected array $params = [] protected CacheAdapterInterface|null $pendingCache = null Lazy-write cache target set by useCache(). When non-null, handle() writes buildDispatcherDump() to this cache after a successful rebuild on cache miss, then clears the property to skip subsequent writes. protected string $pendingCacheKey = "" protected bool $removeExtraSlashes = false protected array $routeMeta = [] Single-source per-route metadata cache. One entry per route, keyed by the route's intrinsic id. Replaces the previous per-method-bucket replication of metadata arrays. Built once in rebuildMethodIndex(). Shape: routeMeta[routeId] = [ "pattern": string, // compiled pattern "isRegex": bool, "hostname": string|null, "hostRegex": string|null, "beforeMatch": callable|null ] protected array $routes = [] protected array $staticByMethod = [] Static-route hash, populated by rebuildMethodIndex(). For each method bucket (including "*"), maps URI => list of routes whose compiled pattern is a literal string equal to that URI. protected array $staticShadowedByMethod = [] Shadow-detection map. If staticShadowedByMethod[method][uri] is set, the static URI in that bucket is shadowed by a later-attached regex route - the fast path MUST NOT be used; fall through to the dynamic loop so the regex wins (reverse-iteration semantics). protected int $uriSource = self::URI_SOURCE_GET_URL protected bool $wasMatched = false public function add(
string $pattern,
mixed $paths = null,
mixed $httpMethods = null,
int $position = Router::POSITION_LAST
): RouteInterface;
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
);
public function addConnect(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addDelete(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addGet(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addHead(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addOptions(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addPatch(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addPost(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addPurge(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addPut(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
public function addTrace(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
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
);
public function getActionName(): string;