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 · Phalcon\Traits\Php\FileTrait
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.
$invoice = new Invoices();
$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;
if ($invoice->save() === false) {
echo "Umh, We can store invoices: ";
$messages = $invoice->getMessages();
foreach ($messages as $message) {
echo $message;
}
} else {
echo "Great, a new invoice was saved successfully!";
}
Magic property and method resolution:
__get($property) resolves in order: a relation alias (returning unsaved
dirtyRelated records first, then a non-reusable single related model held
in the related cache - resultsets and reusable relations are never served
from that cache - otherwise the freshly fetched related records); then a
get<Property>() getter when one exists; otherwise it raises an
"undefined property" notice and returns null.
__call() / __callStatic($method, $arguments) resolve the findBy<Field>,
findFirstBy<Field>, and countBy<Field> magic finders through
invokeFinder(). The instance __call() additionally tries relation getters
and a behavior/listener missingMethod() hook. An unresolved method throws
Phalcon\Mvc\Model\Exceptions\MethodNotFound.
@template T of static
stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Mvc\Model- implementsPhalcon\Mvc\EntityInterface,Phalcon\Mvc\ModelInterface,Phalcon\Mvc\Model\ResultInterface,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\Hydration\CloneResultMapHydrate · Phalcon\Mvc\Model\ManagerInterface · Phalcon\Mvc\Model\MetaDataInterface · Phalcon\Mvc\Model\Query · Phalcon\Mvc\Model\QueryInterface · Phalcon\Mvc\Model\Query\Builder · Phalcon\Mvc\Model\Query\BuilderInterface · Phalcon\Mvc\Model\Relation · Phalcon\Mvc\Model\RelationInterface · Phalcon\Mvc\Model\ResultInterface · Phalcon\Mvc\Model\Resultset · Phalcon\Mvc\Model\ResultsetInterface · Phalcon\Mvc\Model\TransactionInterface · Phalcon\Mvc\Model\ValidationFailed · Phalcon\Support\Collection · Phalcon\Support\Collection\CollectionInterface · Phalcon\Support\Settings · ReflectionClass · ReflectionProperty
Method Summary¶
public
__call(string $method,array $arguments)
Handles method calls when a method is not implemented
public
__callStatic(string $method,array $arguments)
Handles method calls when a static method is not implemented
public
__construct(mixed $data = null,DiInterface $container = null,ManagerInterface $modelsManager = null)
Phalcon\Mvc\Model constructor
public
__get( string $property )
Magic method to get related records using the relation alias as a
public
bool
__isset( string $property )
Magic method to check if a property is a valid relation
public
array
__serialize()
Serializes a model
public
__set(string $property,mixed $value)
Magic method to assign values to the the model
public
void
__unserialize( array $data )
Unserializes an array to the model
public
void
addBehavior( BehaviorInterface $behavior )
Setups a behavior in a model
public
ModelInterface
appendMessage( MessageInterface $message )
Appends a customized message on the validation process
public
void
appendMessagesFrom( mixed $model )
**
public
ModelInterface
assign(array $data,mixed $whiteList = null,mixed $dataColumnMap = null)
Assigns values to a model from an array
public
double|ResultsetInterface
average( array $parameters = [] )
Returns the average value on a column for a result-set of rows matching
public
ModelInterface
cloneResult(ModelInterface $base,array $data,int $dirtyState = 0)
Assigns values to a model from an array returning a new model
public
ModelInterface
cloneResultMap(mixed $base,array $data,mixed $columnMap,int $dirtyState = 0,bool $keepSnapshots = null)
Assigns values to a model from an array, returning a new model.
public
cloneResultMapHydrate(array $data,mixed $columnMap,int $hydrationMode)
Returns an hydrated result based on the data and the column map
public
int|ResultsetInterface
count( mixed $parameters = null )
Counts how many records match the specified conditions.
public
bool
create()
Inserts a model instance. If the instance already exists in the
public
bool
delete()
Deletes a model instance. Returning true on success or false otherwise.
public
bool
doSave( CollectionInterface $visited )
Inserted or updates model instance, expects a visited list of objects.
public
array
dump()
Returns a simple representation of the object that can be used with
public
ResultsetInterface
find( mixed $parameters = null )
Query for a set of records that match the specified conditions
public
mixed|null
findFirst( mixed $parameters = null )
Query the first record that matches the specified conditions
public
bool
fireEvent( string $eventName )
Fires an event, implicitly calls behaviors and listeners in the events
public
bool
fireEventCancel( string $eventName )
Fires an event, implicitly calls behaviors and listeners in the events
public
array
getChangedFields()
Returns a list of changed values.
public
int
getDirtyState()
Returns one of the DIRTY_STATE_* constants telling if the record exists
public
EventsManagerInterface|null
getEventsManager()
Returns the custom events manager or null if there is no custom events manager
public
MessageInterface[]
getMessages( mixed $filter = null )
Returns array of validation messages
public
ManagerInterface
getModelsManager()
Returns the models manager related to the entity instance
public
MetaDataInterface
getModelsMetaData()
{@inheritdoc}
public
array
getOldSnapshotData()
Returns the internal old snapshot data
public
int
getOperationMade()
Returns the type of the latest operation performed by the ORM
public
AdapterInterface
getReadConnection()
Gets the connection used to read data for the model
public
string
getReadConnectionService()
Returns the DependencyInjection connection service name used to read data
public
getRelated(string $alias,mixed $arguments = null)
Returns related records based on defined relations
public
string|null
getSchema()
Returns schema name where the mapped table is located
public
array
getSnapshotData()
Returns the internal snapshot data
public
string
getSource()
Returns the table name mapped in the model
public
TransactionInterface|null
getTransaction()
public
array
getUpdatedFields()
Returns a list of updated values.
public
AdapterInterface
getWriteConnection()
Gets the connection used to write data to the model
public
string
getWriteConnectionService()
Returns the DependencyInjection connection service name used to write
public
bool
hasChanged(mixed $fieldName = null,bool $allFields = false)
Check if a specific attribute has changed
public
bool
hasSnapshotData()
Checks if the object has internal snapshot data
public
bool
hasUpdated(mixed $fieldName = null,bool $allFields = false)
Check if a specific attribute was updated
public
bool
isRelationshipLoaded( string $relationshipAlias )
Checks if saved related records have already been loaded.
public
array
jsonSerialize()
Serializes the object for json_encode
public
mixed
maximum( mixed $parameters = null )
Returns the maximum value of a column for a result-set of rows that match
public
mixed
minimum( mixed $parameters = null )
Returns the minimum value of a column for a result-set of rows that match
public
CriteriaInterface
query( DiInterface $container = null )
Create a criteria for a specific model
public
mixed|null
readAttribute( string $attribute )
Reads an attribute value by its name
public
ModelInterface
refresh()
Refreshes the model attributes re-querying the record from the database
public
bool
save()
Inserts or updates a model instance. Returning true on success or false
public
string|null
serialize()
Serializes the object ignoring connections, services, related objects or
public
void
setConnectionService( string $connectionService )
Sets the DependencyInjection connection service name
public
ModelInterface|bool
setDirtyState( int $dirtyState )
Sets the dirty state of the object using one of the DIRTY_STATE_* constants
public
setEventsManager( EventsManagerInterface $eventsManager )
Sets a custom events manager
public
setOldSnapshotData(array $data,mixed $columnMap = null)
Sets the record's old snapshot data.
public
void
setReadConnectionService( string $connectionService )
Sets the DependencyInjection connection service name used to read data
public
void
setSnapshotData(array $data,mixed $columnMap = null)
Sets the record's snapshot data.
public
ModelInterface
setSync(mixed $elements = null,bool $enabled = true)
Marks one or more many-to-many relationships to be synchronized (or not)
public
ModelInterface
setTransaction( TransactionInterface $transaction )
Sets a transaction related to the Model instance
public
void
setWriteConnectionService( string $connectionService )
Sets the DependencyInjection connection service name used to write data
public
void
setup( array $options )
Enables/disables options in the ORM.
public
void
skipOperation( bool $skip )
Skips the current operation forcing a success state
public
double|ResultsetInterface
sum( mixed $parameters = null )
Calculates the sum on a column for a result-set of rows that match the
public
array
toArray(mixed $columns = null,mixed $useGetter = true)
Returns the instance as an array representation
public
void
unserialize( string $data )
Unserializes the object from a serialized string
public
bool
update()
Updates a model instance. If the instance does not exist in the
public
bool
validationHasFailed()
Check whether validation process has generated any messages
public
void
writeAttribute(string $attribute,mixed $value)
Writes an attribute value by its name
protected
void
allowEmptyStringValues( array $attributes )
Sets a list of attributes that must be skipped from the
protected
Relation
belongsTo(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = [])
Setup a reverse 1-1 or n-1 relation between two models
protected
cancelOperation()
Cancel the current operation
protected
bool
checkForeignKeysRestrict()
Reads "belongs to" relations and check the virtual foreign keys when
protected
bool
checkForeignKeysReverseCascade()
Reads both "hasMany" and "hasOne" relations and checks the virtual
protected
bool
checkForeignKeysReverseRestrict()
Reads both "hasMany" and "hasOne" relations and checks the virtual
protected
array
collectRelatedToSave()
Collects previously queried (belongs-to, has-one and has-one-through)
protected
bool
doLowInsert(MetaDataInterface $metaData,AdapterInterface $connection,mixed $table,mixed $identityField)
Sends a pre-build INSERT SQL statement to the relational database system
protected
bool
doLowUpdate(MetaDataInterface $metaData,AdapterInterface $connection,mixed $table)
Sends a pre-build UPDATE SQL statement to the relational database system
protected
getRelatedRecords(string $modelName,string $method,array $arguments)
Returns related records defined relations depending on the method name.
protected
mixed
groupResult(string $functionName,string $alias,mixed $parameters = null)
Generate a PHQL SELECT statement for an aggregate
protected
bool
has(MetaDataInterface $metaData,AdapterInterface $connection)
Checks whether the current record already exists
protected
Relation
hasMany(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = [])
Setup a 1-n relation between two models
protected
Relation
hasManyToMany(mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referenceModel,mixed $referencedFields,array $options = [])
Setup an n-n relation between two models, through an intermediate
protected
Relation
hasOne(mixed $fields,string $referenceModel,mixed $referencedFields,array $options = [])
Setup a 1-1 relation between two models
protected
Relation
hasOneThrough(mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referenceModel,mixed $referencedFields,array $options = [])
Setup a 1-1 relation between two models, through an intermediate
protected
invokeFinder(string $method,array $arguments)
Try to check if the query must invoke a finder
protected
void
keepSnapshots( bool $keepSnapshot )
Sets if the model must keep the original record snapshot in memory
protected
bool
possibleSetter(string $property,mixed $value)
Check for, and attempt to use, possible setter.
protected
bool
postSave(bool $success,bool $exists)
Executes internal events after save a record
protected
bool
postSaveRelatedRecords(AdapterInterface $connection,mixed $related,CollectionInterface $visited)
Save the related records assigned in the has-one/has-many relations
protected
bool
preSave(MetaDataInterface $metaData,bool $exists,mixed $identityField)
Executes internal hooks before save a record
protected
bool
preSaveRelatedRecords(AdapterInterface $connection,mixed $related,CollectionInterface $visited)
Saves related records that must be stored prior to save the master record
protected
ModelInterface
setSchema( string $schema )
Sets schema name where the mapped table is located
protected
ModelInterface
setSource( string $source )
Sets the table name to which model should be mapped
protected
void
skipAttributes( array $attributes )
Sets a list of attributes that must be skipped from the
protected
void
skipAttributesOnCreate( array $attributes )
Sets a list of attributes that must be skipped from the
protected
void
skipAttributesOnUpdate( array $attributes )
Sets a list of attributes that must be skipped from the
protected
void
useDynamicUpdate( bool $dynamicUpdate )
Sets if a model must use dynamic update instead of the all-field update
protected
bool
validate( ValidationInterface $validator )
Executes validators on every validation call
Constants¶
int
DIRTY_STATE_DETACHED = 2
int
DIRTY_STATE_PERSISTENT = 0
int
DIRTY_STATE_TRANSIENT = 1
int
OP_CREATE = 1
int
OP_DELETE = 3
int
OP_NONE = 0
int
OP_UPDATE = 2
string
TRANSACTION_INDEX = "transaction"
Properties¶
protected
array
$dirtyRelated = []
protected
int
$dirtyState = 1
protected
array
$errorMessages = []
protected
ManagerInterface|null
$modelsManager = null
protected
MetaDataInterface|null
$modelsMetaData = null
protected
array
$oldSnapshot = []
protected
int
$operationMade = 0
protected
array
$rawValues = []
protected
array
$related = []
protected
bool
$skipped = false
protected
array
$snapshot = []
protected
array
$syncRelated = []
Per-save many-to-many sync overrides, keyed by lowercased relation
alias (or "*" wildcard) => bool. Cleared after each save().
protected
TransactionInterface|null
$transaction = null
protected
string|null
$uniqueKey = null
protected
array
$uniqueParams = []
protected
array
$uniqueTypes = []
Methods¶
__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 Invoices extends Model
{
public function initialize()
{
$this->addBehavior(
new Timestampable(
[
"beforeCreate" => [
"field" => "created_at",
"format" => "Y-m-d",
],
]
)
);
$this->addBehavior(
new Timestampable(
[
"beforeUpdate" => [
"field" => "updated_at",
"format" => "Y-m-d",
],
]
)
);
}
}
appendMessage()¶
Appends a customized message on the validation process
use Phalcon\Mvc\Model;
use Phalcon\Messages\Message as Message;
class Invoices extends Model
{
public function beforeSave()
{
if ($this->name === "Peter") {
$message = new Message(
"Sorry, but an invoice cannot be named Peter"
);
$this->appendMessage($message);
}
}
}
appendMessagesFrom()¶
** Append messages to this model from another Model.
assign()¶
public function assign(
array $data,
mixed $whiteList = null,
mixed $dataColumnMap = null
): ModelInterface;
Assigns values to a model from an array
$invoice->assign(
[
"type" => "mechanical",
"name" => "Test Invoice",
"year" => 1952,
]
);
// Assign by db row, column map needed
$invoice->assign(
$dbRow,
[
"db_type" => "type",
"db_name" => "name",
"db_year" => "year",
]
);
// Allow assign only name and year
$invoice->assign(
$_POST,
[
"name",
"year",
]
);
// By default assign method will use setters if exist, you can disable it by using ini_set to directly use properties
ini_set("phalcon.orm.disable_assign_setters", true);
$invoice->assign(
$_POST,
[
"name",
"year",
]
);
average()¶
Returns the average value on a column for a result-set of rows matching the specified conditions.
Returned value will be a float for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the average of each group.
// What's the average price of invoices?
$average = Invoices::average(
[
"column" => "inv_total",
]
);
echo "The average price is ", $average, "\n";
// What's the average price of paid invoices?
$average = Invoices::average(
[
"inv_status_flag = 1",
"column" => "inv_total",
]
);
echo "The average price of paid invoices is ", $average, "\n";
cloneResult()¶
public static function cloneResult(
ModelInterface $base,
array $data,
int $dirtyState = 0
): ModelInterface;
Assigns values to a model from an array returning a new model
$invoice = Phalcon\Mvc\Model::cloneResult(
new Invoices(),
[
"type" => "mechanical",
"name" => "Test Invoice",
"year" => 1952,
]
);
cloneResultMap()¶
public static function cloneResultMap(
mixed $base,
array $data,
mixed $columnMap,
int $dirtyState = 0,
bool $keepSnapshots = null
): ModelInterface;
Assigns values to a model from an array, returning a new model.
$invoice = \Phalcon\Mvc\Model::cloneResultMap(
new Invoices(),
[
"type" => "mechanical",
"name" => "Test Invoice",
"year" => 1952,
]
);
cloneResultMapHydrate()¶
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 invoices are there?
$number = Invoices::count();
echo "There are ", $number, "\n";
// How many paid invoices are there?
$number = Invoices::count("inv_status_flag = 1");
echo "There are ", $number, " paid invoices\n";
create()¶
Inserts a model instance. If the instance already exists in the persistence it will throw an exception Returning true on success or false otherwise.
// Creating a new invoice
$invoice = new Invoices();
$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;
$invoice->create();
// Passing an array to create
$invoice = new Invoices();
$invoice->assign(
[
"type" => "mechanical",
"name" => "Test Invoice",
"year" => 1952,
]
);
$invoice->create();
delete()¶
Deletes a model instance. Returning true on success or false otherwise.
$invoice = Invoices::findFirst("id=100");
$invoice->delete();
$invoices = Invoices::find("inv_status_flag = 1");
foreach ($invoices as $invoice) {
$invoice->delete();
}
doSave()¶
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 invoices are there?
$invoices = Invoices::find();
echo "There are ", count($invoices), "\n";
// How many paid invoices are there?
$invoices = Invoices::find(
"inv_status_flag = 1"
);
echo "There are ", count($invoices), "\n";
// Get and print virtual invoices ordered by name
$invoices = Invoices::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($invoices as $invoice) {
echo $invoice->inv_title, "\n";
}
// Get first 100 virtual invoices ordered by name
$invoices = Invoices::find(
[
"type = 'virtual'",
"order" => "name",
"limit" => 100,
]
);
foreach ($invoices as $invoice) {
echo $invoice->inv_title, "\n";
}
// encapsulate find it into an running transaction esp. useful for application unit-tests
// or complex business logic where we wanna control which transactions are used.
$myTransaction = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction->begin();
$newInvoices = new Invoices();
$newInvoices->setTransaction($myTransaction);
$newInvoices->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newInvoices->save();
$resultInsideTransaction = Invoices::find(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$resultOutsideTransaction = Invoices::find(['name' => 'test']);
foreach ($setInsideTransaction as $invoice) {
echo $invoice->inv_title, "\n";
}
foreach ($setOutsideTransaction as $invoice) {
echo $invoice->inv_title, "\n";
}
// reverts all not commited changes
$myTransaction->rollback();
// creating two different transactions
$myTransaction1 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction1->begin();
$myTransaction2 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction2->begin();
// add a new invoices
$firstNewInvoices = new Invoices();
$firstNewInvoices->setTransaction($myTransaction1);
$firstNewInvoices->assign(
[
'name' => 'first-transaction-invoice',
'type' => 'mechanical',
'year' => 1944,
]
);
$firstNewInvoices->save();
$secondNewInvoices = new Invoices();
$secondNewInvoices->setTransaction($myTransaction2);
$secondNewInvoices->assign(
[
'name' => 'second-transaction-invoice',
'type' => 'fictional',
'year' => 1984,
]
);
$secondNewInvoices->save();
// this transaction will find the invoice.
$resultInFirstTransaction = Invoices::find(
[
'name' => 'first-transaction-invoice',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the invoice.
$resultInSecondTransaction = Invoices::find(
[
'name' => 'first-transaction-invoice',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction won't find the invoice.
$resultOutsideAnyExplicitTransaction = Invoices::find(
[
'name' => 'first-transaction-invoice',
]
);
// this transaction won't find the invoice.
$resultInFirstTransaction = Invoices::find(
[
'name' => 'second-transaction-invoice',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction will find the invoice.
$resultInSecondTransaction = Invoices::find(
[
'name' => 'second-transaction-invoice',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the invoice.
$resultOutsideAnyExplicitTransaction = Invoices::find(
[
'name' => 'second-transaction-invoice',
]
);
$transaction1->rollback();
$transaction2->rollback();
findFirst()¶
Query the first record that matches the specified conditions
// What's the first invoice in invoices table?
$invoice = Invoices::findFirst();
echo "The invoice name is ", $invoice->inv_title;
// What's the first paid invoice in invoices table?
$invoice = Invoices::findFirst(
"inv_status_flag = 1"
);
echo "The first paid invoice name is ", $invoice->inv_title;
// Get first virtual invoice ordered by name
$invoice = Invoices::findFirst(
[
"type = 'virtual'",
"order" => "name",
]
);
echo "The first virtual invoice name is ", $invoice->inv_title;
// behaviour with transaction
$myTransaction = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction->begin();
$newInvoices = new Invoices();
$newInvoices->setTransaction($myTransaction);
$newInvoices->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newInvoices->save();
$findsAInvoices = Invoices::findFirst(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$doesNotFindAInvoices = Invoices::findFirst(
[
'name' => 'test',
]
);
var_dump($findAInvoices);
var_dump($doesNotFindAInvoices);
$transaction->commit();
$doesFindTheInvoicesNow = Invoices::findFirst(
[
'name' => 'test',
]
);
fireEvent()¶
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.
$invoices = Invoices::findFirst();
print_r($invoices->getChangedFields()); // []
$invoices->deleted = 'Y';
$invoices->getChangedFields();
print_r($invoices->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
$invoice = new Invoices();
$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;
if ($invoice->save() === false) {
echo "Umh, We can't store invoices right now ";
$messages = $invoice->getMessages();
foreach ($messages as $message) {
echo $message;
}
} else {
echo "Great, a new invoice was saved successfully!";
}
getModelsManager()¶
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.
$invoices = Invoices::findFirst();
print_r($invoices->getChangedFields()); // []
$invoices->deleted = 'Y';
$invoices->getChangedFields();
print_r($invoices->getChangedFields()); // ["deleted"]
$invoices->save();
print_r($invoices->getChangedFields()); // []
print_r($invoices->getUpdatedFields()); // ["deleted"]
getWriteConnection()¶
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
$invoice = new Invoices();
$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;
$invoice->create();
$invoice->inv_status_flag = "hydraulic";
$hasChanged = $invoice->hasChanged("type"); // returns true
$hasChanged = $invoice->hasChanged(["type", "name"]); // returns true
$hasChanged = $invoice->hasChanged(["type", "name"], true); // returns false
hasSnapshotData()¶
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.
$invoice = Invoices::findFirst();
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // false
$invoicesParts = $invoice->getOrdersProducts(['id > 0']);
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // false
$invoicesParts = $invoice->getOrdersProducts(); // or $invoice->ordersProducts
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // true
$invoice->ordersProducts = [new OrdersProducts()];
var_dump($invoice->isRelationshipLoaded('ordersProducts')); // false
jsonSerialize()¶
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 invoice id?
$id = Invoices::maximum(
[
"column" => "id",
]
);
echo "The maximum invoice id is: ", $id, "\n";
// What is the maximum id of paid invoices?
$sum = Invoices::maximum(
[
"inv_status_flag = 1",
"column" => "id",
]
);
echo "The maximum invoice id of paid invoices is ", $id, "\n";
minimum()¶
Returns the minimum value of a column for a result-set of rows that match the specified conditions
// What is the minimum invoice id?
$id = Invoices::minimum(
[
"column" => "id",
]
);
echo "The minimum invoice id is: ", $id;
// What is the minimum id of paid invoices?
$sum = Invoices::minimum(
[
"inv_status_flag = 1",
"column" => "id",
]
);
echo "The minimum invoice id of paid invoices is ", $id;
query()¶
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 invoice
$invoice = new Invoices();
$invoice->inv_status_flag = "mechanical";
$invoice->inv_title = "Test Invoice";
$invoice->inv_total = 1952;
$invoice->save();
// Updating an invoice name
$invoice = Invoices::findFirst("id = 100");
$invoice->inv_title = "Biomass";
$invoice->save();
serialize()¶
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();
$invoice = new Invoices();
$invoice->setTransaction($transaction);
$invoice->inv_title = "WALL·E";
$invoice->created_at = date("Y-m-d");
if ($invoice->save() === false) {
$transaction->rollback("Can't save invoice");
}
$invoicePart = new OrdersProducts();
$invoicePart->setTransaction($transaction);
$invoicePart->type = "head";
if ($invoicePart->save() === false) {
$transaction->rollback("Invoices part cannot be saved");
}
$transaction->commit();
} catch (TxFailed $e) {
echo "Failed, reason: ", $e->getMessage();
}
setWriteConnectionService()¶
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 invoices?
$sum = Invoices::sum(
[
"column" => "inv_total",
]
);
echo "The total price of invoices is ", $sum, "\n";
// How much are paid invoices?
$sum = Invoices::sum(
[
"inv_status_flag = 1",
"column" => "inv_total",
]
);
echo "The total price of paid invoices is ", $sum, "\n";
toArray()¶
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 Invoices extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->allowEmptyStringValues(
[
"name",
]
);
}
}
belongsTo()¶
protected function belongsTo(
mixed $fields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup a reverse 1-1 or n-1 relation between two models
class OrdersProducts extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->belongsTo(
"oxp_ord_id",
Invoices::class,
"id"
);
}
}
cancelOperation()¶
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 Invoices extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany(
"id",
OrdersProducts::class,
"oxp_ord_id"
);
}
}
hasManyToMany()¶
protected function hasManyToMany(
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup an n-n relation between two models, through an intermediate relation
class Invoices extends \Phalcon\Mvc\Model
{
public function initialize()
{
// Setup a many-to-many relation to Parts through OrdersProducts
$this->hasManyToMany(
"id",
OrdersProducts::class,
"oxp_ord_id",
"oxp_prd_id",
Products::class,
"id",
);
}
}
hasOne()¶
protected function hasOne(
mixed $fields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup a 1-1 relation between two models
class Invoices extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasOne(
"id",
InvoicesDescription::class,
"oxp_ord_id"
);
}
}
hasOneThrough()¶
protected function hasOneThrough(
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referenceModel,
mixed $referencedFields,
array $options = []
): Relation;
Setup a 1-1 relation between two models, through an intermediate relation
class Invoices extends \Phalcon\Mvc\Model
{
public function initialize()
{
// Setup a 1-1 relation to one item from Parts through OrdersProducts
$this->hasOneThrough(
"id",
OrdersProducts::class,
"oxp_ord_id",
"oxp_prd_id",
Products::class,
"id",
);
}
}
invokeFinder()¶
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 Invoices 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 Invoices 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 Invoices 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 Invoices 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 Invoices 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.
<?php
$invoices = Invoices::query()
->where("inv_cst_id = :customerId:")
->bind(["customerId" => 1])
->createBuilder();
distinct()¶
Sets SELECT DISTINCT / SELECT ALL flag
execute()¶
Executes a find using the parameters built with the criteria
forUpdate()¶
Adds the "for_update" parameter to the criteria
fromInput()¶
public static function fromInput(
DiInterface $container,
string $modelName,
array $data,
string $operator = "AND"
): CriteriaInterface;
Builds a Phalcon\Mvc\Model\Criteria based on an input array like $_POST
getColumns()¶
Returns the columns to be queried
getConditions()¶
Returns the conditions parameter in the criteria
getDI()¶
Returns the DependencyInjector container
getGroupBy()¶
Returns the group clause in the criteria
getHaving()¶
Returns the having clause in the criteria
getLimit()¶
Returns the limit parameter in the criteria, which will be
- An integer if 'limit' was set without an 'offset'
- An array with 'number' and 'offset' keys if an offset was set with the limit
- NULL if limit has not been set
getModelName()¶
Returns an internal model name on which the criteria will be applied
getOrderBy()¶
Returns the order clause in the criteria
getParams()¶
Returns all the parameters defined in the criteria
getWhere()¶
Returns the conditions parameter in the criteria
groupBy()¶
Adds the group-by clause to the criteria
having()¶
Adds the having clause to the criteria
inWhere()¶
Appends an IN condition to the current conditions
innerJoin()¶
public function innerJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
Adds an INNER join to the query
<?php
$criteria->innerJoin(
Invoices::class
);
$criteria->innerJoin(
Invoices::class,
"inv_cst_id = Customers.cst_id"
);
$criteria->innerJoin(
Invoices::class,
"i.inv_cst_id = Customers.cst_id",
"i"
);
join()¶
public function join(
string $model,
mixed $conditions = null,
mixed $alias = null,
mixed $type = null
): CriteriaInterface;
Adds an INNER join to the query
<?php
$criteria->join(
Invoices::class
);
$criteria->join(
Invoices::class,
"inv_cst_id = Customers.cst_id"
);
$criteria->join(
Invoices::class,
"i.inv_cst_id = Customers.cst_id",
"i"
);
$criteria->join(
Invoices::class,
"i.inv_cst_id = Customers.cst_id",
"i",
"LEFT"
);
leftJoin()¶
public function leftJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
Adds a LEFT join to the query
limit()¶
Adds the limit parameter to the criteria.
notBetweenWhere()¶
Appends a NOT BETWEEN condition to the current conditions
notInWhere()¶
Appends a NOT IN condition to the current conditions
orWhere()¶
public function orWhere(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
Appends a condition to the current conditions using an OR operator
orderBy()¶
Adds the order-by clause to the criteria
rightJoin()¶
public function rightJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
Adds a RIGHT join to the query
setDI()¶
Sets the DependencyInjector container
setModelName()¶
Set a model on which the query will be executed
sharedLock()¶
Adds the "shared_lock" parameter to the criteria
where()¶
public function where(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
Sets the conditions parameter in the criteria
Mvc\Model\CriteriaInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\CriteriaInterface
Interface for Phalcon\Mvc\Model\Criteria
Phalcon\Mvc\Model\CriteriaInterface
Uses Phalcon\Di\DiInterface
Method Summary¶
public
CriteriaInterface
andWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null)
Appends a condition to the current conditions using an AND operator
public
CriteriaInterface
betweenWhere(string $expr,mixed $minimum,mixed $maximum)
Appends a BETWEEN condition to the current conditions
public
CriteriaInterface
bind( array $bindParams )
Sets the bound parameters in the criteria
public
CriteriaInterface
bindTypes( array $bindTypes )
Sets the bind types in the criteria
public
CriteriaInterface
cache( array $cache )
Sets the cache options in the criteria
public
CriteriaInterface
conditions( string $conditions )
Adds the conditions parameter to the criteria
public
CriteriaInterface
distinct( mixed $distinct )
Sets SELECT DISTINCT / SELECT ALL flag
public
ResultsetInterface
execute()
Executes a find using the parameters built with the criteria
public
CriteriaInterface
forUpdate( bool $forUpdate = true )
Sets the "for_update" parameter to the criteria
public
string|array|null
getColumns()
Returns the columns to be queried
public
string|null
getConditions()
Returns the conditions parameter in the criteria
public
getGroupBy()
Returns the group clause in the criteria
public
getHaving()
Returns the having clause in the criteria
public
int|array|null
getLimit()
Returns the limit parameter in the criteria, which will be
public
string
getModelName()
Returns an internal model name on which the criteria will be applied
public
string|null
getOrderBy()
Returns the order parameter in the criteria
public
array
getParams()
Returns all the parameters defined in the criteria
public
string|null
getWhere()
Returns the conditions parameter in the criteria
public
CriteriaInterface
groupBy( mixed $group )
Adds the group-by clause to the criteria
public
CriteriaInterface
having( mixed $having )
Adds the having clause to the criteria
public
CriteriaInterface
inWhere(string $expr,array $values)
Appends an IN condition to the current conditions
public
CriteriaInterface
innerJoin(string $model,mixed $conditions = null,mixed $alias = null)
Adds an INNER join to the query
public
CriteriaInterface
leftJoin(string $model,mixed $conditions = null,mixed $alias = null)
Adds a LEFT join to the query
public
CriteriaInterface
limit(int $limit,int $offset = 0)
Sets the limit parameter to the criteria
public
CriteriaInterface
notBetweenWhere(string $expr,mixed $minimum,mixed $maximum)
Appends a NOT BETWEEN condition to the current conditions
public
CriteriaInterface
notInWhere(string $expr,array $values)
Appends a NOT IN condition to the current conditions
public
CriteriaInterface
orWhere(string $conditions,mixed $bindParams = null,mixed $bindTypes = null)
Appends a condition to the current conditions using an OR operator
public
CriteriaInterface
orderBy( string $orderColumns )
Adds the order-by parameter to the criteria
public
CriteriaInterface
rightJoin(string $model,mixed $conditions = null,mixed $alias = null)
Adds a RIGHT join to the query
public
CriteriaInterface
setModelName( string $modelName )
Set a model on which the query will be executed
public
CriteriaInterface
sharedLock( bool $sharedLock = true )
Sets the "shared_lock" parameter to the criteria
public
CriteriaInterface
where(string $conditions,mixed $bindParams = null,mixed $bindTypes = null)
Sets the conditions parameter in the criteria
Methods¶
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
conditions()¶
Adds the conditions parameter to the criteria
distinct()¶
Sets SELECT DISTINCT / SELECT ALL flag
execute()¶
Executes a find using the parameters built with the criteria
forUpdate()¶
Sets the "for_update" parameter to the criteria
getColumns()¶
Returns the columns to be queried
getConditions()¶
Returns the conditions parameter in the criteria
getGroupBy()¶
Returns the group clause in the criteria
getHaving()¶
Returns the having clause in the criteria
getLimit()¶
Returns the limit parameter in the criteria, which will be
- An integer if 'limit' was set without an 'offset'
- An array with 'number' and 'offset' keys if an offset was set with the limit
- NULL if limit has not been set
getModelName()¶
Returns an internal model name on which the criteria will be applied
getOrderBy()¶
Returns the order parameter in the criteria
getParams()¶
Returns all the parameters defined in the criteria
getWhere()¶
Returns the conditions parameter in the criteria
groupBy()¶
Adds the group-by clause to the criteria
having()¶
Adds the having clause to the criteria
inWhere()¶
Appends an IN condition to the current conditions
innerJoin()¶
public function innerJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
Adds an INNER join to the query
$criteria->innerJoin(
Orders::class
);
$criteria->innerJoin(
Orders::class,
"r.ord_id = OrdersProducts.oxp_ord_id"
);
$criteria->innerJoin(
Orders::class,
"r.ord_id = OrdersProducts.oxp_ord_id",
"r"
);
leftJoin()¶
public function leftJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
Adds a LEFT join to the query
limit()¶
Sets the limit parameter to the criteria
notBetweenWhere()¶
Appends a NOT BETWEEN condition to the current conditions
notInWhere()¶
Appends a NOT IN condition to the current conditions
orWhere()¶
public function orWhere(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
Appends a condition to the current conditions using an OR operator
orderBy()¶
Adds the order-by parameter to the criteria
rightJoin()¶
public function rightJoin(
string $model,
mixed $conditions = null,
mixed $alias = null
): CriteriaInterface;
Adds a RIGHT join to the query
setModelName()¶
Set a model on which the query will be executed
sharedLock()¶
Sets the "shared_lock" parameter to the criteria
where()¶
public function where(
string $conditions,
mixed $bindParams = null,
mixed $bindTypes = null
): CriteriaInterface;
Sets the conditions parameter in the criteria
Mvc\Model\Exception¶
Class Source on GitHub
Phalcon\Mvc\Model\Exception
Exceptions thrown in Phalcon\Mvc\Model* classes will use this class
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Behavior\Exceptions\MissingRequiredOptionPhalcon\Mvc\Model\Exceptions\BelongsToRequiresObjectPhalcon\Mvc\Model\Exceptions\BindTypeNotDefinedPhalcon\Mvc\Model\Exceptions\CannotResolveAttributePhalcon\Mvc\Model\Exceptions\ColumnNotInMapPhalcon\Mvc\Model\Exceptions\ColumnNotInTableColumnsPhalcon\Mvc\Model\Exceptions\ColumnNotInTableMapPhalcon\Mvc\Model\Exceptions\CorruptColumnTypePhalcon\Mvc\Model\Exceptions\CursorIsImmutablePhalcon\Mvc\Model\Exceptions\DataTypeNotDefinedPhalcon\Mvc\Model\Exceptions\HandlerMustImplementBindablePhalcon\Mvc\Model\Exceptions\IdentityNotInColumnMapPhalcon\Mvc\Model\Exceptions\IdentityNotInTableColumnsPhalcon\Mvc\Model\Exceptions\IndexNotInCursorPhalcon\Mvc\Model\Exceptions\IndexNotInRowPhalcon\Mvc\Model\Exceptions\InvalidConnectionServicePhalcon\Mvc\Model\Exceptions\InvalidContainerPhalcon\Mvc\Model\Exceptions\InvalidDumpResultKeyPhalcon\Mvc\Model\Exceptions\InvalidFindParametersPhalcon\Mvc\Model\Exceptions\InvalidGetModelNameReturnPhalcon\Mvc\Model\Exceptions\InvalidModelNamePhalcon\Mvc\Model\Exceptions\InvalidModelsManagerServicePhalcon\Mvc\Model\Exceptions\InvalidModelsMetadataServicePhalcon\Mvc\Model\Exceptions\InvalidResultsetCacheServicePhalcon\Mvc\Model\Exceptions\InvalidReturnedRecordPhalcon\Mvc\Model\Exceptions\InvalidSerializationDataPhalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailablePhalcon\Mvc\Model\Exceptions\MethodNotFoundPhalcon\Mvc\Model\Exceptions\MissingMethodNamePhalcon\Mvc\Model\Exceptions\MissingModelClassNamePhalcon\Mvc\Model\Exceptions\ModelCouldNotLoadPhalcon\Mvc\Model\Exceptions\ModelOrmServicesUnavailablePhalcon\Mvc\Model\Exceptions\PrimaryKeyAttributeNotSetPhalcon\Mvc\Model\Exceptions\PrimaryKeyRequiredPhalcon\Mvc\Model\Exceptions\PropertyNotAccessiblePhalcon\Mvc\Model\Exceptions\RecordCannotRefreshPhalcon\Mvc\Model\Exceptions\RecordNotPersistedPhalcon\Mvc\Model\Exceptions\ReferencedFieldsMismatchPhalcon\Mvc\Model\Exceptions\RelationAliasMustBeStringPhalcon\Mvc\Model\Exceptions\RelationNotDefinedPhalcon\Mvc\Model\Exceptions\RelationRequiresObjectOrArrayPhalcon\Mvc\Model\Exceptions\ResultsetColumnNotInMapPhalcon\Mvc\Model\Exceptions\RowIsImmutablePhalcon\Mvc\Model\Exceptions\SnapshotsDisabledPhalcon\Mvc\Model\Exceptions\StaticMethodRequiresOneArgumentPhalcon\Mvc\Model\Exceptions\UnknownRelationTypePhalcon\Mvc\Model\Exceptions\UpdateSnapshotDisabledPhalcon\Mvc\Model\MetaData\Exceptions\CannotObtainTableColumnsPhalcon\Mvc\Model\MetaData\Exceptions\ColumnMapNotArrayPhalcon\Mvc\Model\MetaData\Exceptions\ContainerRequiredPhalcon\Mvc\Model\MetaData\Exceptions\CorruptedMetaDataPhalcon\Mvc\Model\MetaData\Exceptions\InvalidContainerPhalcon\Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModelPhalcon\Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritablePhalcon\Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailedPhalcon\Mvc\Model\MetaData\Exceptions\NoAnnotationsForClassPhalcon\Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClassPhalcon\Mvc\Model\MetaData\Exceptions\TableNotInDatabasePhalcon\Mvc\Model\Query\Exceptions\AmbiguousColumnPhalcon\Mvc\Model\Query\Exceptions\AmbiguousJoinRelationPhalcon\Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholdersPhalcon\Mvc\Model\Query\Exceptions\BindTypeRequiresArrayPhalcon\Mvc\Model\Query\Exceptions\BindValueRequiredPhalcon\Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMapPhalcon\Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalidPhalcon\Mvc\Model\Query\Exceptions\Builder\ModelRequiredPhalcon\Mvc\Model\Query\Exceptions\Builder\NoPrimaryKeyPhalcon\Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailablePhalcon\Mvc\Model\Query\Exceptions\ColumnNotInDomainPhalcon\Mvc\Model\Query\Exceptions\ColumnNotInSelectedModelsPhalcon\Mvc\Model\Query\Exceptions\CorruptedAstPhalcon\Mvc\Model\Query\Exceptions\CorruptedDeleteAstPhalcon\Mvc\Model\Query\Exceptions\CorruptedInsertAstPhalcon\Mvc\Model\Query\Exceptions\CorruptedSelectAstPhalcon\Mvc\Model\Query\Exceptions\CorruptedUpdateAstPhalcon\Mvc\Model\Query\Exceptions\DeleteMultipleNotSupportedPhalcon\Mvc\Model\Query\Exceptions\DuplicateAliasPhalcon\Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValuePhalcon\Mvc\Model\Query\Exceptions\InsertColumnCountMismatchPhalcon\Mvc\Model\Query\Exceptions\InvalidCachedResultsetPhalcon\Mvc\Model\Query\Exceptions\InvalidCachingOptionsPhalcon\Mvc\Model\Query\Exceptions\InvalidColumnDefinitionPhalcon\Mvc\Model\Query\Exceptions\InvalidInjectedManagerPhalcon\Mvc\Model\Query\Exceptions\InvalidInjectedMetadataPhalcon\Mvc\Model\Query\Exceptions\InvalidQueryCacheServicePhalcon\Mvc\Model\Query\Exceptions\InvalidResultsetClassPhalcon\Mvc\Model\Query\Exceptions\InvalidResultsetRowClassPhalcon\Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsedPhalcon\Mvc\Model\Query\Exceptions\JoinFieldCountMismatchPhalcon\Mvc\Model\Query\Exceptions\MissingCacheKeyPhalcon\Mvc\Model\Query\Exceptions\MissingMetaDataPhalcon\Mvc\Model\Query\Exceptions\MissingModelAttributePhalcon\Mvc\Model\Query\Exceptions\MissingModelsManagerPhalcon\Mvc\Model\Query\Exceptions\MixedDatabaseSystemsPhalcon\Mvc\Model\Query\Exceptions\ModelSourceNotFoundPhalcon\Mvc\Model\Query\Exceptions\ModelsListNotLoadedPhalcon\Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupportedPhalcon\Mvc\Model\Query\Exceptions\NoModelForAliasPhalcon\Mvc\Model\Query\Exceptions\PhqlColumnNotInMapPhalcon\Mvc\Model\Query\Exceptions\ReadConnectionMissingPhalcon\Mvc\Model\Query\Exceptions\RelationshipNotFoundPhalcon\Mvc\Model\Query\Exceptions\ResultsetClassNotFoundPhalcon\Mvc\Model\Query\Exceptions\ResultsetNonCacheablePhalcon\Mvc\Model\Query\Exceptions\ResultsetRowClassNotFoundPhalcon\Mvc\Model\Query\Exceptions\UnknownBindTypePhalcon\Mvc\Model\Query\Exceptions\UnknownColumnTypePhalcon\Mvc\Model\Query\Exceptions\UnknownJoinTypePhalcon\Mvc\Model\Query\Exceptions\UnknownModelOrAliasPhalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpressionPhalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpressionTypePhalcon\Mvc\Model\Query\Exceptions\UnknownPhqlStatementPhalcon\Mvc\Model\Query\Exceptions\UpdateMultipleNotSupportedPhalcon\Mvc\Model\Query\Exceptions\WriteConnectionMissingPhalcon\Mvc\Model\Transaction\ExceptionPhalcon\Mvc\Model\ValidationFailed
Mvc\Model\Exceptions\BelongsToRequiresObject¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\BelongsToRequiresObject
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\BindTypeNotDefined¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\BindTypeNotDefined
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\CannotResolveAttribute¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\CannotResolveAttribute
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ColumnNotInMap¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ColumnNotInMap
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ColumnNotInTableColumns¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ColumnNotInTableColumns
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ColumnNotInTableMap¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ColumnNotInTableMap
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\CorruptColumnType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\CorruptColumnType
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\CursorIsImmutable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\CursorIsImmutable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\DataTypeNotDefined¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\DataTypeNotDefined
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\HandlerMustImplementBindable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\HandlerMustImplementBindable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\IdentityNotInColumnMap¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\IdentityNotInColumnMap
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\IdentityNotInTableColumns¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\IdentityNotInTableColumns
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\IndexNotInCursor¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\IndexNotInCursor
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\IndexNotInRow¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\IndexNotInRow
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidConnectionService¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidConnectionService
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidContainer¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidContainer
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidDumpResultKey¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidDumpResultKey
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidFindParameters¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidFindParameters
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidGetModelNameReturn¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidGetModelNameReturn
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidModelName¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidModelName
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidModelsManagerService¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidModelsManagerService
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidModelsMetadataService¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidModelsMetadataService
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidResultsetCacheService¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidResultsetCacheService
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidReturnedRecord¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidReturnedRecord
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\InvalidSerializationData¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\InvalidSerializationData
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ManagerOrmServicesUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\MethodNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\MethodNotFound
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\MissingMethodName¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\MissingMethodName
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\MissingModelClassName¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\MissingModelClassName
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ModelCouldNotLoad¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ModelCouldNotLoad
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ModelOrmServicesUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ModelOrmServicesUnavailable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\PrimaryKeyAttributeNotSet
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\PrimaryKeyRequired¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\PrimaryKeyRequired
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\PropertyNotAccessible¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\PropertyNotAccessible
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\RecordCannotRefresh¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\RecordCannotRefresh
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\RecordNotPersisted¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\RecordNotPersisted
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ReferencedFieldsMismatch¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ReferencedFieldsMismatch
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\RelationAliasMustBeString¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\RelationAliasMustBeString
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\RelationNotDefined¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\RelationNotDefined
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\RelationRequiresObjectOrArray¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\RelationRequiresObjectOrArray
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\ResultsetColumnNotInMap¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\ResultsetColumnNotInMap
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\RowIsImmutable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\RowIsImmutable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\SnapshotsDisabled¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\SnapshotsDisabled
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\StaticMethodRequiresOneArgument¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\StaticMethodRequiresOneArgument
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\UnknownRelationType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\UnknownRelationType
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Exceptions\UpdateSnapshotDisabled¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Exceptions\UpdateSnapshotDisabled
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Hydration\CaseInsensitiveColumnMap¶
Class Source on GitHub
Phalcon\Mvc\Model\Hydration\CaseInsensitiveColumnMap
Method Summary¶
Methods¶
caseInsensitiveColumnMap()¶
Mvc\Model\Hydration\CloneResultMapHydrate¶
Class Source on GitHub
Phalcon\Mvc\Model\Hydration\CloneResultMapHydrate
Uses Phalcon\Mvc\Model\Exceptions\ColumnNotInMap · Phalcon\Mvc\Model\Resultset · Phalcon\Support\Settings
Method Summary¶
Methods¶
cloneResultMapHydrate()¶
public static function cloneResultMapHydrate(
array $data,
mixed $columnMap,
int $hydrationMode,
string $calledClass = "Phalcon\\Mvc\\Model"
);
Mvc\Model\Manager¶
Class Source on GitHub
Phalcon\Mvc\Model\Manager
This components controls the initialization of models, keeping record of relations between the different models of the application.
A ModelsManager is injected to a model via a Dependency Injector/Services Container such as Phalcon\Di\Di.
use Phalcon\Di\Di;
use Phalcon\Mvc\Model\Manager as ModelsManager;
$di = new Di();
$di->set(
"modelsManager",
function() {
return new ModelsManager();
}
);
$invoice = new Invoices($di);
Phalcon\Mvc\Model\Manager- implementsPhalcon\Mvc\Model\ManagerInterface,Phalcon\Di\InjectionAwareInterface,Phalcon\Events\EventsAwareInterface
Uses Phalcon\Contracts\Mvc\Model\Relation\CacheKeyProvider · Phalcon\Db\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Exceptions\InvalidConnectionService · Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable · Phalcon\Mvc\Model\Exceptions\ModelCouldNotLoad · Phalcon\Mvc\Model\Exceptions\ReferencedFieldsMismatch · Phalcon\Mvc\Model\Exceptions\RelationAliasMustBeString · Phalcon\Mvc\Model\Exceptions\UnknownRelationType · Phalcon\Mvc\Model\Query\Builder · Phalcon\Mvc\Model\Query\BuilderInterface · Phalcon\Mvc\Model\Query\StatusInterface · Phalcon\Support\Settings · ReflectionClass · ReflectionProperty
Method Summary¶
public
__destruct()
Destroys the current PHQL cache
public
void
addBehavior(ModelInterface $model,BehaviorInterface $behavior)
Binds a behavior to a model
public
RelationInterface
addBelongsTo(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = [])
Setup a relation reverse many to one between two models
public
RelationInterface
addHasMany(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = [])
Setup a relation 1-n between two models
public
RelationInterface
addHasManyToMany(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = [])
Setups a relation n-m between two models
public
RelationInterface
addHasOne(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = [])
Setup a 1-1 relation between two models
public
RelationInterface
addHasOneThrough(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = [])
Setups a relation 1-1 between two models using an intermediate model
public
void
clearReusableObjects()
Clears the internal reusable list
public
BuilderInterface
createBuilder( mixed $params = null )
Creates a Phalcon\Mvc\Model\Query\Builder
public
QueryInterface
createQuery( string $phql )
Creates a Phalcon\Mvc\Model\Query without execute it
public
mixed
executeQuery(string $phql,mixed $placeholders = null,mixed $types = null)
Creates a Phalcon\Mvc\Model\Query and execute it
public
bool
existsBelongsTo(string $modelName,string $modelRelation)
Checks whether a model has a belongsTo relation with another model
public
bool
existsHasMany(string $modelName,string $modelRelation)
Checks whether a model has a hasMany relation with another model
public
bool
existsHasManyToMany(string $modelName,string $modelRelation)
Checks whether a model has a hasManyToMany relation with another model
public
bool
existsHasOne(string $modelName,string $modelRelation)
Checks whether a model has a hasOne relation with another model
public
bool
existsHasOneThrough(string $modelName,string $modelRelation)
Checks whether a model has a hasOneThrough relation with another model
public
RelationInterface[]|array
getBelongsTo( ModelInterface $model )
Gets all the belongsTo relations defined in a model
public
ResultsetInterface|bool
getBelongsToRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null)
Gets belongsTo related records from a model
public
BuilderInterface|null
getBuilder()
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null
public
string
getConnectionService(ModelInterface $model,array $connectionServices)
Returns the connection service name used to read or write data related to
public
EventsManagerInterface|null
getCustomEventsManager( ModelInterface $model )
Returns a custom events manager related to a model or null if there is
public
DiInterface
getDI()
Returns the DependencyInjector container
public
EventsManagerInterface|null
getEventsManager()
Returns the internal event manager
public
RelationInterface[]|array
getHasMany( ModelInterface $model )
Gets hasMany relations defined on a model
public
ResultsetInterface|bool
getHasManyRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null)
Gets hasMany related records from a model
public
RelationInterface[]|array
getHasManyToMany( ModelInterface $model )
Gets hasManyToMany relations defined on a model
public
array
getHasOne( ModelInterface $model )
Gets hasOne relations defined on a model
public
RelationInterface[]
getHasOneAndHasMany( ModelInterface $model )
Gets hasOne relations defined on a model
public
ModelInterface|bool
getHasOneRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null)
Gets belongsTo related records from a model
public
RelationInterface[]|array
getHasOneThrough( ModelInterface $model )
Gets hasOneThrough relations defined on a model
public
ModelInterface|null
getLastInitialized()
Get last initialized model
public
QueryInterface
getLastQuery()
Returns the last query created or executed in the models manager
public
string
getModelPrefix()
Returns the prefix for all model sources.
public
string|null
getModelSchema( ModelInterface $model )
Returns the mapped schema for a model
public
string
getModelSource( ModelInterface $model )
Returns the mapped source for a model
public
AdapterInterface
getReadConnection( ModelInterface $model )
Returns the connection to read data related to a model
public
string
getReadConnectionService( ModelInterface $model )
Returns the connection service name used to read data related to a model
public
RelationInterface|bool
getRelationByAlias(string $modelName,string $alias)
Returns a relation by its alias
public
getRelationRecords(RelationInterface $relation,ModelInterface $record,mixed $parameters = null,string $method = null)
Helper method to query records based on a relation definition
public
RelationInterface[]
getRelations( string $modelName )
Query all the relationships defined on a model
public
RelationInterface[]|bool
getRelationsBetween(string $first,string $second)
Query the first relationship defined between two models
public
getReusableRecords(string $modelName,string $key)
Returns a reusable object from the internal list
public
AdapterInterface
getWriteConnection( ModelInterface $model )
Returns the connection to write data related to a model
public
string
getWriteConnectionService( ModelInterface $model )
Returns the connection service name used to write data related to a model
public
bool
hasBelongsTo(string $modelName,string $modelRelation)
Checks whether a model has a belongsTo relation with another model
public
bool
hasHasMany(string $modelName,string $modelRelation)
Checks whether a model has a hasMany relation with another model
public
bool
hasHasManyToMany(string $modelName,string $modelRelation)
Checks whether a model has a hasManyToMany relation with another model
public
bool
hasHasOne(string $modelName,string $modelRelation)
Checks whether a model has a hasOne relation with another model
public
bool
hasHasOneThrough(string $modelName,string $modelRelation)
Checks whether a model has a hasOneThrough relation with another model
public
bool
initialize( ModelInterface $model )
Initializes a model in the model manager
public
bool
isInitialized( string $className )
Check whether a model is already initialized
public
bool
isKeepingSnapshots( ModelInterface $model )
Checks if a model is keeping snapshots for the queried records
public
bool
isUsingDynamicUpdate( ModelInterface $model )
Checks if a model is using dynamic update instead of all-field update
public
bool
isVisibleModelProperty(ModelInterface $model,string $property)
Check whether a model property is declared as public.
public
void
keepSnapshots(ModelInterface $model,bool $keepSnapshots)
Sets if a model must keep snapshots
public
ModelInterface
load( string $modelName )
Loads a model throwing an exception if it does not exist
public
missingMethod(ModelInterface $model,string $eventName,mixed $data)
Dispatch an event to the listeners and behaviors
public
notifyEvent(string $eventName,ModelInterface $model)
Receives events generated in the models and dispatches them to an
public
void
registerWrite( ModelInterface $model )
Marks the model's write connection service as written-to for the
public
void
removeBehavior(ModelInterface $model,string $behaviorClass)
Removes a behavior from a model
public
void
resetConnectionState()
Clears the per-request sticky write tracking. Call this between
public
void
setConnectionService(ModelInterface $model,string $connectionService)
Sets both write and read connection service for a model
public
void
setCustomEventsManager(ModelInterface $model,EventsManagerInterface $eventsManager)
Sets a custom events manager for a specific model
public
void
setDI( DiInterface $container )
Sets the DependencyInjector container
public
void
setEventsManager( EventsManagerInterface $eventsManager )
Sets a global events manager
public
void
setModelPrefix( string $prefix )
Sets the prefix for all model sources.
public
void
setModelSchema(ModelInterface $model,string $schema)
Sets the mapped schema for a model
public
void
setModelSource(ModelInterface $model,string $source)
Sets the mapped source for a model
public
void
setReadConnectionService(ModelInterface $model,string $connectionService)
Sets read connection service for a model
public
void
setReusableRecords(string $modelName,string $key,mixed $records)
Stores a reusable record in the internal list
public
void
setSticky( bool $sticky )
Enables or disables sticky connections. When enabled, once a model has
public
void
setWriteConnectionService(ModelInterface $model,string $connectionService)
Sets write connection service for a model
public
void
useDynamicUpdate(ModelInterface $model,bool $dynamicUpdate)
Sets if a model must use dynamic update instead of the all-field update
protected
AdapterInterface
getConnection(ModelInterface $model,array $connectionServices)
Returns the connection to read or write data related to a model
protected
array
mergeFindParameters(mixed $findParamsOne,mixed $findParamsTwo)
Merge two arrays of find parameters
Properties¶
protected
array
$aliases = []
protected
array
$behaviors = []
Models' behaviors
protected
array
$belongsTo = []
Belongs to relations
protected
array
$belongsToSingle = []
All the relationships by model
protected
BuilderInterface|null
$builder = null
protected
DiInterface|null
$container = null
protected
array
$customEventsManager = []
protected
array
$dirtyWriteServices = []
Write connection services that have been written to during the current
request cycle. Used by the sticky mechanism to route reads to the write
connection after a write.
protected
array
$dynamicUpdate = []
Does the model use dynamic update, instead of updating all rows?
protected
EventsManagerInterface|null
$eventsManager = null
protected
array
$hasMany = []
Has many relations
protected
array
$hasManySingle = []
Has many relations by model
protected
array
$hasManyToMany = []
Has many-Through relations
protected
array
$hasManyToManySingle = []
Has many-Through relations by model
protected
array
$hasOne = []
Has one relations
protected
array
$hasOneSingle = []
Has one relations by model
protected
array
$hasOneThrough = []
Has one through relations
protected
array
$hasOneThroughSingle = []
Has one through relations by model
protected
array
$initialized = []
Mark initialized models
protected
array
$keepSnapshots = []
protected
ModelInterface|null
$lastInitialized = null
Last model initialized
protected
QueryInterface|null
$lastQuery = null
Last query created/executed
protected
array
$modelVisibility = []
protected
string
$prefix = ""
protected
array
$readConnectionServices = []
protected
array
$reusable = []
Stores a list of reusable instances
protected
array
$schemas = []
protected
array
$sources = []
protected
bool
$sticky = false
Whether reads should stick to the write connection after a write has
occurred during the current request cycle.
protected
array
$writeConnectionServices = []
Methods¶
__destruct()¶
Destroys the current PHQL cache
addBehavior()¶
Binds a behavior to a model
addBelongsTo()¶
public function addBelongsTo(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setup a relation reverse many to one between two models
addHasMany()¶
public function addHasMany(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setup a relation 1-n between two models
addHasManyToMany()¶
public function addHasManyToMany(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setups a relation n-m between two models
addHasOne()¶
public function addHasOne(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setup a 1-1 relation between two models
addHasOneThrough()¶
public function addHasOneThrough(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setups a relation 1-1 between two models using an intermediate model
clearReusableObjects()¶
Clears the internal reusable list
createBuilder()¶
Creates a Phalcon\Mvc\Model\Query\Builder
createQuery()¶
Creates a Phalcon\Mvc\Model\Query without execute it
executeQuery()¶
public function executeQuery(
string $phql,
mixed $placeholders = null,
mixed $types = null
): mixed;
Creates a Phalcon\Mvc\Model\Query and execute it
$model = new Invoices();
$manager = $model->getModelsManager();
// \Phalcon\Mvc\Model\Resultset\Simple
$manager->executeQuery('SELECT * FROM Invoices');
// \Phalcon\Mvc\Model\Resultset\Complex
$manager->executeQuery('SELECT COUNT(inv_status_flag) FROM Invoices GROUP BY inv_status_flag');
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('INSERT INTO Invoices (inv_id) VALUES (1)');
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('UPDATE Invoices SET inv_id = 0 WHERE inv_id = :id:', ['id' => 1]);
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('DELETE FROM Invoices WHERE inv_id = :id:', ['id' => 1]);
existsBelongsTo()¶
Checks whether a model has a belongsTo relation with another model
existsHasMany()¶
Checks whether a model has a hasMany relation with another model
existsHasManyToMany()¶
Checks whether a model has a hasManyToMany relation with another model
existsHasOne()¶
Checks whether a model has a hasOne relation with another model
existsHasOneThrough()¶
Checks whether a model has a hasOneThrough relation with another model
getBelongsTo()¶
Gets all the belongsTo relations defined in a model
getBelongsToRecords()¶
public function getBelongsToRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
Gets belongsTo related records from a model
getBuilder()¶
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null
getConnectionService()¶
Returns the connection service name used to read or write data related to a model depending on the connection services
getCustomEventsManager()¶
Returns a custom events manager related to a model or null if there is no related events manager
getDI()¶
Returns the DependencyInjector container
getEventsManager()¶
Returns the internal event manager
getHasMany()¶
Gets hasMany relations defined on a model
getHasManyRecords()¶
public function getHasManyRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
Gets hasMany related records from a model
getHasManyToMany()¶
Gets hasManyToMany relations defined on a model
getHasOne()¶
Gets hasOne relations defined on a model
getHasOneAndHasMany()¶
Gets hasOne relations defined on a model
getHasOneRecords()¶
public function getHasOneRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ModelInterface|bool;
Gets belongsTo related records from a model
getHasOneThrough()¶
Gets hasOneThrough relations defined on a model
getLastInitialized()¶
Get last initialized model
getLastQuery()¶
Returns the last query created or executed in the models manager
getModelPrefix()¶
Returns the prefix for all model sources.
getModelSchema()¶
Returns the mapped schema for a model
getModelSource()¶
Returns the mapped source for a model
getReadConnection()¶
Returns the connection to read data related to a model
getReadConnectionService()¶
Returns the connection service name used to read data related to a model
getRelationByAlias()¶
Returns a relation by its alias
getRelationRecords()¶
public function getRelationRecords(
RelationInterface $relation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
);
Helper method to query records based on a relation definition
getRelations()¶
Query all the relationships defined on a model
getRelationsBetween()¶
Query the first relationship defined between two models
getReusableRecords()¶
Returns a reusable object from the internal list
getWriteConnection()¶
Returns the connection to write data related to a model
getWriteConnectionService()¶
Returns the connection service name used to write data related to a model
hasBelongsTo()¶
Checks whether a model has a belongsTo relation with another model
hasHasMany()¶
Checks whether a model has a hasMany relation with another model
hasHasManyToMany()¶
Checks whether a model has a hasManyToMany relation with another model
hasHasOne()¶
Checks whether a model has a hasOne relation with another model
hasHasOneThrough()¶
Checks whether a model has a hasOneThrough relation with another model
initialize()¶
Initializes a model in the model manager
isInitialized()¶
Check whether a model is already initialized
isKeepingSnapshots()¶
Checks if a model is keeping snapshots for the queried records
isUsingDynamicUpdate()¶
Checks if a model is using dynamic update instead of all-field update
isVisibleModelProperty()¶
Check whether a model property is declared as public.
keepSnapshots()¶
Sets if a model must keep snapshots
load()¶
Loads a model throwing an exception if it does not exist
missingMethod()¶
Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented
notifyEvent()¶
Receives events generated in the models and dispatches them to an events-manager if available. Notify the behaviors that are listening in the model
registerWrite()¶
Marks the model's write connection service as written-to for the current request cycle. Used by the sticky mechanism to route subsequent reads to the write connection.
removeBehavior()¶
Removes a behavior from a model
resetConnectionState()¶
Clears the per-request sticky write tracking. Call this between requests in long-running runtimes (e.g. Swoole, RoadRunner) where the manager instance is reused across requests.
setConnectionService()¶
Sets both write and read connection service for a model
setCustomEventsManager()¶
public function setCustomEventsManager(
ModelInterface $model,
EventsManagerInterface $eventsManager
): void;
Sets a custom events manager for a specific model
setDI()¶
Sets the DependencyInjector container
setEventsManager()¶
Sets a global events manager
setModelPrefix()¶
Sets the prefix for all model sources.
use Phalcon\Mvc\Model\Manager;
$di->set(
"modelsManager",
function () {
$modelsManager = new Manager();
$modelsManager->setModelPrefix("wp_");
return $modelsManager;
}
);
$invoices = new Invoices();
echo $invoices->getSource(); // wp_co_invoices
$param string $prefix
setModelSchema()¶
Sets the mapped schema for a model
setModelSource()¶
Sets the mapped source for a model
setReadConnectionService()¶
Sets read connection service for a model
setReusableRecords()¶
Stores a reusable record in the internal list
setSticky()¶
Enables or disables sticky connections. When enabled, once a model has written to its write connection during the current request cycle, any further reads for that write service use the write connection.
setWriteConnectionService()¶
public function setWriteConnectionService(
ModelInterface $model,
string $connectionService
): void;
Sets write connection service for a model
useDynamicUpdate()¶
Sets if a model must use dynamic update instead of the all-field update
getConnection()¶
protected function getConnection(
ModelInterface $model,
array $connectionServices
): AdapterInterface;
Returns the connection to read or write data related to a model depending on the connection services.
mergeFindParameters()¶
Merge two arrays of find parameters
Mvc\Model\ManagerInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\ManagerInterface
Interface for Phalcon\Mvc\Model\Manager
Phalcon\Mvc\Model\ManagerInterface
Uses Phalcon\Db\Adapter\AdapterInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Query\BuilderInterface · Phalcon\Mvc\Model\Query\StatusInterface
Method Summary¶
public
void
addBehavior(ModelInterface $model,BehaviorInterface $behavior)
Binds a behavior to a model
public
RelationInterface
addBelongsTo(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = [])
Setup a relation reverse 1-1 between two models
public
RelationInterface
addHasMany(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = [])
Setup a relation 1-n between two models
public
RelationInterface
addHasManyToMany(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = [])
Setups a relation n-m between two models
public
RelationInterface
addHasOne(ModelInterface $model,mixed $fields,string $referencedModel,mixed $referencedFields,array $options = [])
Setup a 1-1 relation between two models
public
RelationInterface
addHasOneThrough(ModelInterface $model,mixed $fields,string $intermediateModel,mixed $intermediateFields,mixed $intermediateReferencedFields,string $referencedModel,mixed $referencedFields,array $options = [])
Setups a 1-1 relation between two models using an intermediate table
public
void
clearReusableObjects()
Clears the internal reusable list
public
BuilderInterface
createBuilder( mixed $params = null )
Creates a Phalcon\Mvc\Model\Query\Builder
public
QueryInterface
createQuery( string $phql )
Creates a Phalcon\Mvc\Model\Query without execute it
public
mixed
executeQuery(string $phql,mixed $placeholders = null,mixed $types = null)
Creates a Phalcon\Mvc\Model\Query and execute it
public
RelationInterface[]|array
getBelongsTo( ModelInterface $model )
Gets belongsTo relations defined on a model
public
ResultsetInterface|bool
getBelongsToRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null)
Gets belongsTo related records from a model
public
BuilderInterface|null
getBuilder()
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null
public
RelationInterface[]|array
getHasMany( ModelInterface $model )
Gets hasMany relations defined on a model
public
ResultsetInterface|bool
getHasManyRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null)
Gets hasMany related records from a model
public
RelationInterface[]|array
getHasManyToMany( ModelInterface $model )
Gets hasManyToMany relations defined on a model
public
RelationInterface[]|array
getHasOne( ModelInterface $model )
Gets hasOne relations defined on a model
public
RelationInterface[]
getHasOneAndHasMany( ModelInterface $model )
Gets hasOne relations defined on a model
public
ModelInterface|bool
getHasOneRecords(string $modelName,string $modelRelation,ModelInterface $record,mixed $parameters = null,string $method = null)
Gets hasOne related records from a model
public
RelationInterface[]|array
getHasOneThrough( ModelInterface $model )
Gets hasOneThrough relations defined on a model
public
ModelInterface|null
getLastInitialized()
Get last initialized model
public
QueryInterface
getLastQuery()
Returns the last query created or executed in the models manager
public
string|null
getModelSchema( ModelInterface $model )
Returns the mapped schema for a model
public
string
getModelSource( ModelInterface $model )
Returns the mapped source for a model
public
AdapterInterface
getReadConnection( ModelInterface $model )
Returns the connection to read data related to a model
public
string
getReadConnectionService( ModelInterface $model )
Returns the connection service name used to read data related to a model
public
RelationInterface|bool
getRelationByAlias(string $modelName,string $alias)
Returns a relation by its alias
public
getRelationRecords(RelationInterface $relation,ModelInterface $record,mixed $parameters = null,string $method = null)
Helper method to query records based on a relation definition
public
RelationInterface[]
getRelations( string $modelName )
Query all the relationships defined on a model
public
RelationInterface[]|bool
getRelationsBetween(string $first,string $second)
Query the relations between two models
public
getReusableRecords(string $modelName,string $key)
Returns a reusable object from the internal list
public
AdapterInterface
getWriteConnection( ModelInterface $model )
Returns the connection to write data related to a model
public
string
getWriteConnectionService( ModelInterface $model )
Returns the connection service name used to write data related to a model
public
bool
hasBelongsTo(string $modelName,string $modelRelation)
Checks whether a model has a belongsTo relation with another model
public
bool
hasHasMany(string $modelName,string $modelRelation)
Checks whether a model has a hasMany relation with another model
public
bool
hasHasManyToMany(string $modelName,string $modelRelation)
Checks whether a model has a hasManyToMany relation with another model
public
bool
hasHasOne(string $modelName,string $modelRelation)
Checks whether a model has a hasOne relation with another model
public
bool
hasHasOneThrough(string $modelName,string $modelRelation)
Checks whether a model has a hasOneThrough relation with another model
public
initialize( ModelInterface $model )
Initializes a model in the model manager
public
bool
isInitialized( string $className )
Check of a model is already initialized
public
bool
isKeepingSnapshots( ModelInterface $model )
Checks if a model is keeping snapshots for the queried records
public
bool
isUsingDynamicUpdate( ModelInterface $model )
Checks if a model is using dynamic update instead of all-field update
public
bool
isVisibleModelProperty(ModelInterface $model,string $property)
Check whether a model property is declared as public.
public
void
keepSnapshots(ModelInterface $model,bool $keepSnapshots)
Sets if a model must keep snapshots
public
ModelInterface
load( string $modelName )
Loads a model throwing an exception if it does not exist
public
missingMethod(ModelInterface $model,string $eventName,mixed $data)
Dispatch an event to the listeners and behaviors
public
notifyEvent(string $eventName,ModelInterface $model)
Receives events generated in the models and dispatches them to an events-manager if available
public
void
registerWrite( ModelInterface $model )
Marks the model's write connection service as written-to for the
public
void
removeBehavior(ModelInterface $model,string $behaviorClass)
Removes a behavior from a model
public
void
resetConnectionState()
Clears the per-request sticky write tracking
public
void
setConnectionService(ModelInterface $model,string $connectionService)
Sets both write and read connection service for a model
public
void
setModelSchema(ModelInterface $model,string $schema)
Sets the mapped schema for a model
public
void
setModelSource(ModelInterface $model,string $source)
Sets the mapped source for a model
public
void
setReadConnectionService(ModelInterface $model,string $connectionService)
Sets read connection service for a model
public
void
setReusableRecords(string $modelName,string $key,mixed $records)
Stores a reusable record in the internal list
public
void
setSticky( bool $sticky )
Enables or disables sticky connections
public
setWriteConnectionService(ModelInterface $model,string $connectionService)
Sets write connection service for a model
public
void
useDynamicUpdate(ModelInterface $model,bool $dynamicUpdate)
Sets if a model must use dynamic update instead of the all-field update
Methods¶
addBehavior()¶
Binds a behavior to a model
addBelongsTo()¶
public function addBelongsTo(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setup a relation reverse 1-1 between two models
addHasMany()¶
public function addHasMany(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setup a relation 1-n between two models
addHasManyToMany()¶
public function addHasManyToMany(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setups a relation n-m between two models
addHasOne()¶
public function addHasOne(
ModelInterface $model,
mixed $fields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setup a 1-1 relation between two models
addHasOneThrough()¶
public function addHasOneThrough(
ModelInterface $model,
mixed $fields,
string $intermediateModel,
mixed $intermediateFields,
mixed $intermediateReferencedFields,
string $referencedModel,
mixed $referencedFields,
array $options = []
): RelationInterface;
Setups a 1-1 relation between two models using an intermediate table
clearReusableObjects()¶
Clears the internal reusable list
createBuilder()¶
Creates a Phalcon\Mvc\Model\Query\Builder
createQuery()¶
Creates a Phalcon\Mvc\Model\Query without execute it
executeQuery()¶
public function executeQuery(
string $phql,
mixed $placeholders = null,
mixed $types = null
): mixed;
Creates a Phalcon\Mvc\Model\Query and execute it
getBelongsTo()¶
Gets belongsTo relations defined on a model
getBelongsToRecords()¶
public function getBelongsToRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
Gets belongsTo related records from a model
getBuilder()¶
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null
getHasMany()¶
Gets hasMany relations defined on a model
getHasManyRecords()¶
public function getHasManyRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ResultsetInterface|bool;
Gets hasMany related records from a model
getHasManyToMany()¶
Gets hasManyToMany relations defined on a model
getHasOne()¶
Gets hasOne relations defined on a model
getHasOneAndHasMany()¶
Gets hasOne relations defined on a model
getHasOneRecords()¶
public function getHasOneRecords(
string $modelName,
string $modelRelation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
): ModelInterface|bool;
Gets hasOne related records from a model
getHasOneThrough()¶
Gets hasOneThrough relations defined on a model
getLastInitialized()¶
Get last initialized model
getLastQuery()¶
Returns the last query created or executed in the models manager
getModelSchema()¶
Returns the mapped schema for a model
getModelSource()¶
Returns the mapped source for a model
getReadConnection()¶
Returns the connection to read data related to a model
getReadConnectionService()¶
Returns the connection service name used to read data related to a model
getRelationByAlias()¶
Returns a relation by its alias
getRelationRecords()¶
public function getRelationRecords(
RelationInterface $relation,
ModelInterface $record,
mixed $parameters = null,
string $method = null
);
Helper method to query records based on a relation definition
getRelations()¶
Query all the relationships defined on a model
getRelationsBetween()¶
Query the relations between two models
getReusableRecords()¶
Returns a reusable object from the internal list
getWriteConnection()¶
Returns the connection to write data related to a model
getWriteConnectionService()¶
Returns the connection service name used to write data related to a model
hasBelongsTo()¶
Checks whether a model has a belongsTo relation with another model
hasHasMany()¶
Checks whether a model has a hasMany relation with another model
hasHasManyToMany()¶
Checks whether a model has a hasManyToMany relation with another model
hasHasOne()¶
Checks whether a model has a hasOne relation with another model
hasHasOneThrough()¶
Checks whether a model has a hasOneThrough relation with another model
initialize()¶
Initializes a model in the model manager
isInitialized()¶
Check of a model is already initialized
isKeepingSnapshots()¶
Checks if a model is keeping snapshots for the queried records
isUsingDynamicUpdate()¶
Checks if a model is using dynamic update instead of all-field update
isVisibleModelProperty()¶
Check whether a model property is declared as public.
keepSnapshots()¶
Sets if a model must keep snapshots
load()¶
Loads a model throwing an exception if it does not exist
missingMethod()¶
Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one is implemented
notifyEvent()¶
Receives events generated in the models and dispatches them to an events-manager if available Notify the behaviors that are listening in the model
registerWrite()¶
Marks the model's write connection service as written-to for the current request cycle (sticky connections)
removeBehavior()¶
Removes a behavior from a model
resetConnectionState()¶
Clears the per-request sticky write tracking
setConnectionService()¶
Sets both write and read connection service for a model
setModelSchema()¶
Sets the mapped schema for a model
setModelSource()¶
Sets the mapped source for a model
setReadConnectionService()¶
Sets read connection service for a model
setReusableRecords()¶
Stores a reusable record in the internal list
setSticky()¶
Enables or disables sticky connections
setWriteConnectionService()¶
Sets write connection service for a model
useDynamicUpdate()¶
Sets if a model must use dynamic update instead of the all-field update
Mvc\Model\MetaData¶
Abstract Source on GitHub
Phalcon\Mvc\Model\MetaData
Because Phalcon\Mvc\Model requires meta-data like field names, data types, primary keys, etc. This component collect them and store for further querying by Phalcon\Mvc\Model. Phalcon\Mvc\Model\MetaData can also use adapters to store temporarily or permanently the meta-data.
A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes:
$metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
$attributes = $metaData->getAttributes(
new Invoices()
);
print_r($attributes);
Each model's metadata is stored as two positional arrays addressed by two constant families. Both families count from 0 and therefore share numeric values, so a metadata array is only meaningful together with the family that indexes it. The metadata cache adapters persist these arrays verbatim, so the slot layout is a stored format: reordering a slot invalidates existing caches.
Attribute metadata array (MODELS_* family):
| Slot | Constant | Contents |
|---|---|---|
| 0 | MODELS_ATTRIBUTES |
All mapped attribute (column) names |
| 1 | MODELS_PRIMARY_KEY |
Primary-key attributes |
| 2 | MODELS_NON_PRIMARY_KEY |
Non-primary-key attributes |
| 3 | MODELS_NOT_NULL |
Attributes declared NOT NULL |
| 4 | MODELS_DATA_TYPES |
attribute => column data type |
| 5 | MODELS_DATA_TYPES_NUMERIC |
Attributes with a numeric type |
| 6 | MODELS_DATE_AT |
Reserved (declared, currently unused) |
| 7 | MODELS_DATE_IN |
Reserved (declared, currently unused) |
| 8 | MODELS_IDENTITY_COLUMN |
The auto-increment identity attribute |
| 9 | MODELS_DATA_TYPES_BIND |
attribute => PDO bind type |
| 10 | MODELS_AUTOMATIC_DEFAULT_INSERT |
Attributes omitted from INSERT (DB-defaulted) |
| 11 | MODELS_AUTOMATIC_DEFAULT_UPDATE |
Attributes omitted from UPDATE (DB-defaulted) |
| 12 | MODELS_DEFAULT_VALUES |
attribute => default value |
| 13 | MODELS_EMPTY_STRING_VALUES |
Attributes that keep '' instead of NULL |
Column-map array (MODELS_COLUMN_MAP family), present only when a column map
is defined:
| Slot | Constant | Contents |
|---|---|---|
| 0 | MODELS_COLUMN_MAP |
column => attribute |
| 1 | MODELS_REVERSE_COLUMN_MAP |
attribute => column |
Uses Phalcon\Cache\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\MetaData\Exceptions\ContainerRequired · Phalcon\Mvc\Model\MetaData\Exceptions\CorruptedMetaData · Phalcon\Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel · Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed · Phalcon\Mvc\Model\MetaData\Strategy\Introspection · Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface · Phalcon\Support\Settings · Phalcon\Traits\Support\Helper\Arr\GetTrait
Method Summary¶
public
CacheAdapterInterface|null
getAdapter()
Return the internal cache adapter
public
array
getAttributes( ModelInterface $model )
Returns table attributes names (fields)
public
array
getAutomaticCreateAttributes( ModelInterface $model )
Returns attributes that must be ignored from the INSERT SQL generation
public
array
getAutomaticUpdateAttributes( ModelInterface $model )
Returns attributes that must be ignored from the UPDATE SQL generation
public
array
getBindTypes( ModelInterface $model )
Returns attributes and their bind data types
public
array|null
getColumnMap( ModelInterface $model )
Returns the column map if any
public
string|null
getColumnMapUniqueKey( ModelInterface $model )
Returns a ColumnMap Unique key for meta-data is created using className
public
DiInterface
getDI()
Returns the DependencyInjector container
public
array
getDataTypes( ModelInterface $model )
Returns attributes and their data types
public
array
getDataTypesNumeric( ModelInterface $model )
Returns attributes which types are numerical
public
array
getDefaultValues( ModelInterface $model )
Returns attributes (which have default values) and their default values
public
array
getEmptyStringAttributes( ModelInterface $model )
Returns attributes allow empty strings
public
bool|string|null
getIdentityField( ModelInterface $model )
Returns the name of identity field (if one is present)
public
string|null
getMetaDataUniqueKey( ModelInterface $model )
Returns a MetaData Unique key for meta-data is created using className
public
string|null
getModelUUID(ModelInterface $model,array $row)
Returns the model UniqueID based on model and array row primary key(s) value(s)
public
array
getNonPrimaryKeyAttributes( ModelInterface $model )
Returns an array of fields which are not part of the primary key
public
array
getNotNullAttributes( ModelInterface $model )
Returns an array of not null attributes
public
array
getPrimaryKeyAttributes( ModelInterface $model )
Returns an array of fields which are part of the primary key
public
array|null
getReverseColumnMap( ModelInterface $model )
Returns the reverse column map if any
public
StrategyInterface
getStrategy()
Return the strategy to obtain the meta-data
public
bool
hasAttribute(ModelInterface $model,string $attribute)
Check if a model has certain attribute
public
bool
isEmpty()
Checks if the internal meta-data container is empty
public
bool
modelEquals(ModelInterface $first,ModelInterface $other)
Compares if two models are the same in memory
public
array|null
read( mixed $key )
Reads metadata from the adapter
public
array|null
readColumnMap( ModelInterface $model )
Reads the ordered/reversed column map for certain model
public
array|null
readColumnMapIndex(ModelInterface $model,int $index)
Reads column-map information for certain model using a MODEL_* constant
public
array|null
readMetaData( ModelInterface $model )
Reads the complete meta-data for certain model
public
array|string|null
readMetaDataIndex(ModelInterface $model,int $index)
Reads meta-data for certain model
public
void
reset()
Resets internal meta-data in order to regenerate it
public
void
setAutomaticCreateAttributes(ModelInterface $model,array $attributes)
Set the attributes that must be ignored from the INSERT SQL generation
public
void
setAutomaticUpdateAttributes(ModelInterface $model,array $attributes)
Set the attributes that must be ignored from the UPDATE SQL generation
public
void
setDI( DiInterface $container )
Sets the DependencyInjector container
public
void
setEmptyStringAttributes(ModelInterface $model,array $attributes)
Set the attributes that allow empty string values
public
void
setStrategy( StrategyInterface $strategy )
Set the meta-data extraction strategy
public
void
write(string $key,array $data)
Writes the metadata to adapter
public
void
writeMetaDataIndex(ModelInterface $model,int $index,mixed $data)
Writes meta-data for certain model using a MODEL_* constant
protected
initialize(ModelInterface $model,mixed $key,mixed $table,mixed $schema)
Initialize old behaviour for compatability
protected
bool
initializeColumnMap(ModelInterface $model,mixed $key)
Initialize ColumnMap for a certain table
protected
bool
initializeMetaData(ModelInterface $model,mixed $key)
Initialize the metadata for certain table
Constants¶
int
MODELS_ATTRIBUTES = 0
int
MODELS_AUTOMATIC_DEFAULT_INSERT = 10
int
MODELS_AUTOMATIC_DEFAULT_UPDATE = 11
int
MODELS_COLUMN_MAP = 0
int
MODELS_DATA_TYPES = 4
int
MODELS_DATA_TYPES_BIND = 9
int
MODELS_DATA_TYPES_NUMERIC = 5
int
MODELS_DATE_AT = 6
int
MODELS_DATE_IN = 7
int
MODELS_DEFAULT_VALUES = 12
int
MODELS_EMPTY_STRING_VALUES = 13
int
MODELS_IDENTITY_COLUMN = 8
int
MODELS_NON_PRIMARY_KEY = 2
int
MODELS_NOT_NULL = 3
int
MODELS_PRIMARY_KEY = 1
int
MODELS_REVERSE_COLUMN_MAP = 1
Properties¶
protected
CacheAdapterInterface|null
$adapter = null
protected
array
$columnMap = []
protected
DiInterface|null
$container = null
protected
array
$metaData = []
protected
array
$pendingMetaDataWrites = []
Holds metadata index writes that arrived before the model's metadata was
properly initialized (e.g. skipAttributes() called in a parent model's
initialize() while the child's source had not yet been set). Applied
inside initializeMetaData() after the real schema is loaded.
protected
StrategyInterface|null
$strategy = null
Methods¶
getAdapter()¶
Return the internal cache adapter
getAttributes()¶
Returns table attributes names (fields)
getAutomaticCreateAttributes()¶
Returns attributes that must be ignored from the INSERT SQL generation
getAutomaticUpdateAttributes()¶
Returns attributes that must be ignored from the UPDATE SQL generation
getBindTypes()¶
Returns attributes and their bind data types
getColumnMap()¶
Returns the column map if any
getColumnMapUniqueKey()¶
Returns a ColumnMap Unique key for meta-data is created using className
getDI()¶
Returns the DependencyInjector container
getDataTypes()¶
Returns attributes and their data types
getDataTypesNumeric()¶
Returns attributes which types are numerical
getDefaultValues()¶
Returns attributes (which have default values) and their default values
getEmptyStringAttributes()¶
Returns attributes allow empty strings
getIdentityField()¶
Returns the name of identity field (if one is present)
getMetaDataUniqueKey()¶
Returns a MetaData Unique key for meta-data is created using className
getModelUUID()¶
Returns the model UniqueID based on model and array row primary key(s) value(s)
getNonPrimaryKeyAttributes()¶
Returns an array of fields which are not part of the primary key
getNotNullAttributes()¶
Returns an array of not null attributes
getPrimaryKeyAttributes()¶
Returns an array of fields which are part of the primary key
getReverseColumnMap()¶
Returns the reverse column map if any
getStrategy()¶
Return the strategy to obtain the meta-data
hasAttribute()¶
Check if a model has certain attribute
isEmpty()¶
Checks if the internal meta-data container is empty
modelEquals()¶
Compares if two models are the same in memory
read()¶
Reads metadata from the adapter
readColumnMap()¶
Reads the ordered/reversed column map for certain model
readColumnMapIndex()¶
Reads column-map information for certain model using a MODEL_* constant
readMetaData()¶
Reads the complete meta-data for certain model
readMetaDataIndex()¶
Reads meta-data for certain model
reset()¶
Resets internal meta-data in order to regenerate it
setAutomaticCreateAttributes()¶
Set the attributes that must be ignored from the INSERT SQL generation
setAutomaticUpdateAttributes()¶
Set the attributes that must be ignored from the UPDATE SQL generation
setDI()¶
Sets the DependencyInjector container
setEmptyStringAttributes()¶
Set the attributes that allow empty string values
setStrategy()¶
Set the meta-data extraction strategy
write()¶
Writes the metadata to adapter
writeMetaDataIndex()¶
Writes meta-data for certain model using a MODEL_* constant
print_r(
$metaData->writeColumnMapIndex(
new Invoices(),
MetaData::MODELS_REVERSE_COLUMN_MAP,
[
"leName" => "name",
]
)
);
initialize()¶
final protected function initialize(
ModelInterface $model,
mixed $key,
mixed $table,
mixed $schema
);
Initialize old behaviour for compatability
initializeColumnMap()¶
Initialize ColumnMap for a certain table
initializeMetaData()¶
Initialize the metadata for certain table
Mvc\Model\MetaDataInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\MetaDataInterface
Interface for Phalcon\Mvc\Model\MetaData
Phalcon\Mvc\Model\MetaDataInterface
Uses Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
Method Summary¶
public
array
getAttributes( ModelInterface $model )
Returns table attributes names (fields)
public
array
getAutomaticCreateAttributes( ModelInterface $model )
Returns attributes that must be ignored from the INSERT SQL generation
public
array
getAutomaticUpdateAttributes( ModelInterface $model )
Returns attributes that must be ignored from the UPDATE SQL generation
public
array
getBindTypes( ModelInterface $model )
Returns attributes and their bind data types
public
array|null
getColumnMap( ModelInterface $model )
Returns the column map if any
public
array
getDataTypes( ModelInterface $model )
Returns attributes and their data types
public
array
getDataTypesNumeric( ModelInterface $model )
Returns attributes which types are numerical
public
array
getDefaultValues( ModelInterface $model )
Returns attributes (which have default values) and their default values
public
array
getEmptyStringAttributes( ModelInterface $model )
Returns attributes allow empty strings
public
bool|string|null
getIdentityField( ModelInterface $model )
Returns the name of identity field (if one is present)
public
array
getNonPrimaryKeyAttributes( ModelInterface $model )
Returns an array of fields which are not part of the primary key
public
array
getNotNullAttributes( ModelInterface $model )
Returns an array of not null attributes
public
array
getPrimaryKeyAttributes( ModelInterface $model )
Returns an array of fields which are part of the primary key
public
array|null
getReverseColumnMap( ModelInterface $model )
Returns the reverse column map if any
public
StrategyInterface
getStrategy()
Return the strategy to obtain the meta-data
public
bool
hasAttribute(ModelInterface $model,string $attribute)
Check if a model has certain attribute
public
bool
isEmpty()
Checks if the internal meta-data container is empty
public
array|null
read( string $key )
Reads meta-data from the adapter
public
array|null
readColumnMap( ModelInterface $model )
Reads the ordered/reversed column map for certain model
public
array|null
readColumnMapIndex(ModelInterface $model,int $index)
Reads column-map information for certain model using a MODEL_* constant
public
array|null
readMetaData( ModelInterface $model )
Reads meta-data for certain model
public
array|string|null
readMetaDataIndex(ModelInterface $model,int $index)
Reads meta-data for certain model using a MODEL_* constant
public
reset()
Resets internal meta-data in order to regenerate it
public
setAutomaticCreateAttributes(ModelInterface $model,array $attributes)
Set the attributes that must be ignored from the INSERT SQL generation
public
setAutomaticUpdateAttributes(ModelInterface $model,array $attributes)
Set the attributes that must be ignored from the UPDATE SQL generation
public
void
setEmptyStringAttributes(ModelInterface $model,array $attributes)
Set the attributes that allow empty string values
public
setStrategy( StrategyInterface $strategy )
Set the meta-data extraction strategy
public
void
write(string $key,array $data)
Writes meta-data to the adapter
public
writeMetaDataIndex(ModelInterface $model,int $index,mixed $data)
Writes meta-data for certain model using a MODEL_* constant
Methods¶
getAttributes()¶
Returns table attributes names (fields)
getAutomaticCreateAttributes()¶
Returns attributes that must be ignored from the INSERT SQL generation
getAutomaticUpdateAttributes()¶
Returns attributes that must be ignored from the UPDATE SQL generation
getBindTypes()¶
Returns attributes and their bind data types
getColumnMap()¶
Returns the column map if any
getDataTypes()¶
Returns attributes and their data types
getDataTypesNumeric()¶
Returns attributes which types are numerical
getDefaultValues()¶
Returns attributes (which have default values) and their default values
getEmptyStringAttributes()¶
Returns attributes allow empty strings
getIdentityField()¶
Returns the name of identity field (if one is present)
getNonPrimaryKeyAttributes()¶
Returns an array of fields which are not part of the primary key
getNotNullAttributes()¶
Returns an array of not null attributes
getPrimaryKeyAttributes()¶
Returns an array of fields which are part of the primary key
getReverseColumnMap()¶
Returns the reverse column map if any
getStrategy()¶
Return the strategy to obtain the meta-data
hasAttribute()¶
Check if a model has certain attribute
isEmpty()¶
Checks if the internal meta-data container is empty
read()¶
Reads meta-data from the adapter
readColumnMap()¶
Reads the ordered/reversed column map for certain model
readColumnMapIndex()¶
Reads column-map information for certain model using a MODEL_* constant
readMetaData()¶
Reads meta-data for certain model
readMetaDataIndex()¶
Reads meta-data for certain model using a MODEL_* constant
reset()¶
Resets internal meta-data in order to regenerate it
setAutomaticCreateAttributes()¶
Set the attributes that must be ignored from the INSERT SQL generation
setAutomaticUpdateAttributes()¶
Set the attributes that must be ignored from the UPDATE SQL generation
setEmptyStringAttributes()¶
Set the attributes that allow empty string values
setStrategy()¶
Set the meta-data extraction strategy
write()¶
Writes meta-data to the adapter
writeMetaDataIndex()¶
Writes meta-data for certain model using a MODEL_* constant
Mvc\Model\MetaData\Apcu¶
Class Source on GitHub
Phalcon\Mvc\Model\MetaData\Apcu
Stores model meta-data in the APCu cache. Data will erased if the web server is restarted
By default meta-data is stored for 48 hours (172800 seconds)
You can query the meta-data by printing apcu_fetch('$PMM$') or apcu_fetch('$PMM$my-app-id')
$metaData = new \Phalcon\Mvc\Model\MetaData\Apcu(
[
"prefix" => "my-app-id",
"lifetime" => 86400,
]
);
Phalcon\Mvc\Model\MetaDataPhalcon\Mvc\Model\MetaData\Apcu
Uses Phalcon\Cache\AdapterFactory · Phalcon\Mvc\Model\MetaData
Method Summary¶
Methods¶
__construct()¶
Phalcon\Mvc\Model\MetaData\Apcu constructor
Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\ColumnMapNotArray¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\ColumnMapNotArray
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\ContainerRequired¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\ContainerRequired
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\CorruptedMetaData¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\CorruptedMetaData
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\InvalidContainer¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\InvalidContainer
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\InvalidMetaDataForModel
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\MetaDataStrategyFailed
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Exceptions\TableNotInDatabase¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\MetaData\Exceptions\TableNotInDatabase
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\MetaData\Libmemcached¶
Class Source on GitHub
Phalcon\Mvc\Model\MetaData\Libmemcached
Stores model meta-data in the Memcache.
By default meta-data is stored for 48 hours (172800 seconds)
Phalcon\Mvc\Model\MetaDataPhalcon\Mvc\Model\MetaData\Libmemcached
Uses Phalcon\Cache\AdapterFactory · Phalcon\Mvc\Model\MetaData
Method Summary¶
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
Methods¶
__construct()¶
Phalcon\Mvc\Model\MetaData\Libmemcached constructor
reset()¶
Flush Memcache data and resets internal meta-data in order to regenerate it
Mvc\Model\MetaData\Memory¶
Class Source on GitHub
Phalcon\Mvc\Model\MetaData\Memory
Stores model meta-data in memory. Data will be erased when the request finishes
Phalcon\Mvc\Model\MetaDataPhalcon\Mvc\Model\MetaData\Memory
Uses Phalcon\Mvc\Model\MetaData
Method Summary¶
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
Methods¶
read()¶
Reads the meta-data from temporal memory
write()¶
Writes the meta-data to temporal memory
Mvc\Model\MetaData\Redis¶
Class Source on GitHub
Phalcon\Mvc\Model\MetaData\Redis
Stores model meta-data in the Redis.
By default meta-data is stored for 48 hours (172800 seconds)
use Phalcon\Mvc\Model\MetaData\Redis;
$metaData = new Redis(
[
"host" => "127.0.0.1",
"port" => 6379,
"persistent" => 0,
"lifetime" => 172800,
"index" => 2,
]
);
Phalcon\Mvc\Model\MetaDataPhalcon\Mvc\Model\MetaData\Redis
Uses Phalcon\Cache\AdapterFactory · Phalcon\Mvc\Model\MetaData
Method Summary¶
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
Methods¶
__construct()¶
Phalcon\Mvc\Model\MetaData\Redis constructor
reset()¶
Flush Redis data and resets internal meta-data in order to regenerate it
Mvc\Model\MetaData\Strategy\Annotations¶
Class Source on GitHub
Phalcon\Mvc\Model\MetaData\Strategy\Annotations- implementsPhalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
Uses Phalcon\Db\Column · Phalcon\Di\DiInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\MetaData · Phalcon\Mvc\Model\MetaData\Exceptions\InvalidContainer · Phalcon\Mvc\Model\MetaData\Exceptions\NoAnnotationsForClass · Phalcon\Mvc\Model\MetaData\Exceptions\NoPropertyAnnotationsForClass
Method Summary¶
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
Methods¶
getColumnMaps()¶
Read the model's column map, this can't be inferred
getMetaData()¶
The meta-data is obtained by reading the column descriptions from the database information schema
Mvc\Model\MetaData\Strategy\Introspection¶
Class Source on GitHub
Queries the table meta-data in order to introspect the model's metadata
Phalcon\Mvc\Model\MetaData\Strategy\Introspection- implementsPhalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
Uses Phalcon\Db\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\MetaData · Phalcon\Mvc\Model\MetaData\Exceptions\CannotObtainTableColumns · Phalcon\Mvc\Model\MetaData\Exceptions\ColumnMapNotArray · Phalcon\Mvc\Model\MetaData\Exceptions\TableNotInDatabase
Method Summary¶
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
Methods¶
getColumnMaps()¶
Read the model's column map, this can't be inferred
getMetaData()¶
The meta-data is obtained by reading the column descriptions from the database information schema
Mvc\Model\MetaData\Strategy\StrategyInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
Uses Phalcon\Di\DiInterface · Phalcon\Mvc\ModelInterface
Method Summary¶
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
Methods¶
getColumnMaps()¶
Read the model's column map, this can't be inferred
@todo Not implemented
getMetaData()¶
The meta-data is obtained by reading the column descriptions from the database information schema
Mvc\Model\MetaData\Stream¶
Class Source on GitHub
Phalcon\Mvc\Model\MetaData\Stream
Stores model meta-data in PHP files.
Phalcon\Mvc\Model\MetaDataPhalcon\Mvc\Model\MetaData\Stream
Uses Phalcon\Mvc\Model\MetaData · Phalcon\Mvc\Model\MetaData\Exceptions\MetaDataDirectoryNotWritable · Phalcon\Support\Settings · Phalcon\Traits\Php\FileTrait
Method Summary¶
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
Properties¶
protected
string
$metaDataDir = "./"
Methods¶
__construct()¶
Phalcon\Mvc\Model\MetaData\Files constructor
read()¶
Reads meta-data from files
write()¶
Writes the meta-data to files
Mvc\Model\Query¶
Class Source on GitHub
Phalcon\Mvc\Model\Query
This class takes a PHQL intermediate representation and executes it.
$phql = "SELECT c.price*0.16 AS taxes, c.* FROM Cars AS c JOIN Brands AS b
WHERE b.name = :name: ORDER BY c.name";
$result = $manager->executeQuery(
$phql,
[
"name" => "Lamborghini",
]
);
foreach ($result as $row) {
echo "Name: ", $row->cars->name, "\n";
echo "Price: ", $row->cars->price, "\n";
echo "Taxes: ", $row->taxes, "\n";
}
// with transaction
use Phalcon\Mvc\Model\Query;
use Phalcon\Mvc\Model\Transaction;
// $di needs to have the service "db" registered for this to work
$di = Phalcon\Di\FactoryDefault::getDefault();
$phql = 'SELECT * FROM Invoices';
$myTransaction = new Transaction($di);
$myTransaction->begin();
$newInvoice = new Invoices();
$newInvoice->setTransaction($myTransaction);
$newInvoice->inv_status_flag = 1;
$newInvoice->inv_title = "Test Invoice";
$newInvoice->inv_total = 100;
$newInvoice->save();
$queryWithTransaction = new Query($phql, $di);
$queryWithTransaction->setTransaction($myTransaction);
$resultWithEntries = $queryWithTransaction->execute();
$queryWithOutTransaction = new Query($phql, $di);
$resultWithOutEntries = $queryWithTransaction->execute();
Phalcon\Mvc\Model\Query- implementsPhalcon\Mvc\Model\QueryInterface,Phalcon\Di\InjectionAwareInterface
Uses Phalcon\Db\Adapter\AdapterInterface · Phalcon\Db\Column · Phalcon\Db\DialectInterface · Phalcon\Db\RawValue · Phalcon\Db\ResultInterface · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Query\Exceptions\AmbiguousColumn · Phalcon\Mvc\Model\Query\Exceptions\AmbiguousJoinRelation · Phalcon\Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders · Phalcon\Mvc\Model\Query\Exceptions\BindTypeRequiresArray · Phalcon\Mvc\Model\Query\Exceptions\BindValueRequired · Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInDomain · Phalcon\Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels · Phalcon\Mvc\Model\Query\Exceptions\CorruptedAst · Phalcon\Mvc\Model\Query\Exceptions\CorruptedDeleteAst · Phalcon\Mvc\Model\Query\Exceptions\CorruptedInsertAst · Phalcon\Mvc\Model\Query\Exceptions\CorruptedSelectAst · Phalcon\Mvc\Model\Query\Exceptions\CorruptedUpdateAst · Phalcon\Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported · Phalcon\Mvc\Model\Query\Exceptions\DuplicateAlias · Phalcon\Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue · Phalcon\Mvc\Model\Query\Exceptions\InsertColumnCountMismatch · Phalcon\Mvc\Model\Query\Exceptions\InvalidCachedResultset · Phalcon\Mvc\Model\Query\Exceptions\InvalidCachingOptions · Phalcon\Mvc\Model\Query\Exceptions\InvalidColumnDefinition · Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedManager · Phalcon\Mvc\Model\Query\Exceptions\InvalidInjectedMetadata · Phalcon\Mvc\Model\Query\Exceptions\InvalidQueryCacheService · Phalcon\Mvc\Model\Query\Exceptions\InvalidResultsetClass · Phalcon\Mvc\Model\Query\Exceptions\InvalidResultsetRowClass · Phalcon\Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed · Phalcon\Mvc\Model\Query\Exceptions\JoinFieldCountMismatch · Phalcon\Mvc\Model\Query\Exceptions\MissingCacheKey · Phalcon\Mvc\Model\Query\Exceptions\MissingMetaData · Phalcon\Mvc\Model\Query\Exceptions\MissingModelAttribute · Phalcon\Mvc\Model\Query\Exceptions\MissingModelsManager · Phalcon\Mvc\Model\Query\Exceptions\MixedDatabaseSystems · Phalcon\Mvc\Model\Query\Exceptions\ModelSourceNotFound · Phalcon\Mvc\Model\Query\Exceptions\ModelsListNotLoaded · Phalcon\Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported · Phalcon\Mvc\Model\Query\Exceptions\NoModelForAlias · Phalcon\Mvc\Model\Query\Exceptions\PhqlColumnNotInMap · Phalcon\Mvc\Model\Query\Exceptions\ReadConnectionMissing · Phalcon\Mvc\Model\Query\Exceptions\RelationshipNotFound · Phalcon\Mvc\Model\Query\Exceptions\ResultsetClassNotFound · Phalcon\Mvc\Model\Query\Exceptions\ResultsetNonCacheable · Phalcon\Mvc\Model\Query\Exceptions\ResultsetRowClassNotFound · Phalcon\Mvc\Model\Query\Exceptions\UnknownBindType · Phalcon\Mvc\Model\Query\Exceptions\UnknownColumnType · Phalcon\Mvc\Model\Query\Exceptions\UnknownJoinType · Phalcon\Mvc\Model\Query\Exceptions\UnknownModelOrAlias · Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpression · Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType · Phalcon\Mvc\Model\Query\Exceptions\UnknownPhqlStatement · Phalcon\Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported · Phalcon\Mvc\Model\Query\Exceptions\WriteConnectionMissing · Phalcon\Mvc\Model\Query\Lang · Phalcon\Mvc\Model\Query\Status · Phalcon\Mvc\Model\Query\StatusInterface · Phalcon\Mvc\Model\ResultsetInterface · Phalcon\Mvc\Model\Resultset\Complex · Phalcon\Mvc\Model\Resultset\Simple · Phalcon\Support\Settings
Method Summary¶
public
__construct(string $phql = null,DiInterface $container = null,array $options = [])
Phalcon\Mvc\Model\Query constructor
public
QueryInterface
cache( array $cacheOptions )
Sets the cache parameters of the query
public
void
clean()
Destroys the internal PHQL cache
public
execute(array $bindParams = [],array $bindTypes = [])
Executes a parsed PHQL statement
public
array
getBindParams()
Returns default bind params
public
array
getBindTypes()
Returns default bind types
public
AdapterInterface
getCache()
Returns the current cache backend instance
public
array
getCacheOptions()
Returns the current cache options
public
DiInterface
getDI()
Returns the dependency injection container
public
array
getIntermediate()
Returns the intermediate representation of the PHQL statement
public
string
getResultsetRowClass()
Returns the class that will be used to hydrate rows that are not mapped
public
ModelInterface
getSingleResult(array $bindParams = [],array $bindTypes = [])
Executes the query returning the first result
public
array
getSql()
Returns an associative array with the SQL to be generated by the internal PHQL,
public
TransactionInterface|null
getTransaction()
public
int
getType()
Gets the type of PHQL statement executed
public
bool
getUniqueRow()
Check if the query is programmed to get only the first row in the
public
array
parse()
Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang
public
QueryInterface
setBindParams(array $bindParams,bool $merge = false)
Set default bind parameters
public
QueryInterface
setBindTypes(array $bindTypes,bool $merge = false)
Set default bind parameters
public
void
setDI( DiInterface $container )
Sets the dependency injection container
public
QueryInterface
setIntermediate( array $intermediate )
Allows to set the IR to be executed
public
QueryInterface
setResultsetRowClass( string $resultsetRowClass )
Sets the class used to hydrate rows that are not mapped to a model
public
QueryInterface
setSharedLock( bool $sharedLock = false )
Set SHARED LOCK clause
public
QueryInterface
setTransaction( TransactionInterface $transaction )
allows to wrap a transaction around all queries
public
QueryInterface
setType( int $type )
Sets the type of PHQL statement to be executed
public
QueryInterface
setUniqueRow( bool $uniqueRow )
Tells to the query if only the first row in the resultset must be
protected
StatusInterface
executeDelete(array $intermediate,array $bindParams,array $bindTypes)
Executes the DELETE intermediate representation producing a
protected
StatusInterface
executeInsert(array $intermediate,array $bindParams,array $bindTypes)
Executes the INSERT intermediate representation producing a
protected
ResultsetInterface|array
executeSelect(array $intermediate,array $bindParams,array $bindTypes,bool $simulate = false)
Executes the SELECT intermediate representation producing a
protected
StatusInterface
executeUpdate(array $intermediate,array $bindParams,array $bindTypes)
Executes the UPDATE intermediate representation producing a
protected
array
getCallArgument( array $argument )
Resolves an expression in a single call argument
protected
array
getCaseExpression( array $expr )
Resolves an expression in a single call argument
protected
array
getExpression(array $expr,bool $quoting = true)
Resolves an expression from its intermediate code into an array
protected
array
getFunctionCall( array $expr )
Resolves an expression in a single call argument
protected
array
getGroupClause( array $group )
Returns a processed group clause for a SELECT statement
protected
array
getJoin(ManagerInterface $manager,array $join)
Resolves a JOIN clause checking if the associated models exist
protected
string
getJoinType( array $join )
Resolves a JOIN type
protected
array
getJoins( array $select )
Processes the JOINs in the query returning an internal representation for
protected
array
getLimitClause( array $limitClause )
Returns a processed limit clause for a SELECT statement
protected
array
getMultiJoin(string $joinType,mixed $joinSource,string $modelAlias,string $joinAlias,RelationInterface $relation)
Resolves joins involving many-to-many relations
protected
array
getOrderClause( mixed $order )
Returns a processed order clause for a SELECT statement
protected
array
getQualified( array $expr )
Replaces the model's name to its source name in a qualified-name
protected
AdapterInterface
getReadConnection(ModelInterface $model,array $intermediate = null,array $bindParams = [],array $bindTypes = [])
Gets the read connection from the model if there is no transaction set
protected
ResultsetInterface
getRelatedRecords(ModelInterface $model,array $intermediate,array $bindParams,array $bindTypes)
Query the records on which the UPDATE/DELETE operation will be done
protected
array
getSelectColumn( array $column )
Resolves a column from its intermediate representation into an array
protected
array
getSingleJoin(string $joinType,mixed $joinSource,string $modelAlias,string $joinAlias,RelationInterface $relation)
Resolves joins involving has-one/belongs-to/has-many relations
protected
getTable(ManagerInterface $manager,array $qualifiedName)
Resolves a table in a SELECT statement checking if the model exists
protected
AdapterInterface
getWriteConnection(ModelInterface $model,array $intermediate = null,array $bindParams = [],array $bindTypes = [])
Gets the write connection from the model if there is no transaction
protected
array
prepareDelete()
Analyzes a DELETE intermediate code and produces an array to be executed
protected
array
prepareInsert()
Analyzes an INSERT intermediate code and produces an array to be executed
protected
array
prepareSelect(mixed $ast = null,bool $merge = false)
Analyzes a SELECT intermediate code and produces an array to be executed later
protected
array
prepareUpdate()
Analyzes an UPDATE intermediate code and produces an array to be executed
protected
array
refreshSchemasInIntermediate( array $irPhql )
Refreshes the schema/source of every model referenced in a cached
Constants¶
int
TYPE_DELETE = 303
int
TYPE_INSERT = 306
int
TYPE_SELECT = 309
int
TYPE_UPDATE = 300
Properties¶
protected
array
$ast
protected
array
$bindParams = []
protected
array
$bindTypes = []
protected
mixed|null
$cache = null
protected
array|null
$cacheOptions
protected
DiInterface|null
$container = null
protected
bool
$enableImplicitJoins
protected
array
$intermediate
protected
array|null
$internalPhqlCache
protected
\Phalcon\Mvc\Model\ManagerInterface|null
$manager = null
protected
\Phalcon\Mvc\Model\MetaDataInterface|null
$metaData = null
protected
array
$models = []
protected
array
$modelsInstances = []
protected
int
$nestingLevel = -1
protected
string|null
$phql = null
protected
string
$resultsetRowClass = ""
protected
bool
$sharedLock = false
protected
array
$sqlAliases = []
protected
array
$sqlAliasesModels = []
protected
array
$sqlAliasesModelsInstances = []
protected
array
$sqlColumnAliases = []
protected
array
$sqlModelsAliases = []
protected
TransactionInterface|null
$transaction = null
TransactionInterface so that the query can wrap a transaction
around batch updates and intermediate selects within the transaction.
however if a model got a transaction set inside it will use the local
transaction instead of this one
protected
int|null
$type
protected
bool
$uniqueRow = false
Methods¶
__construct()¶
public function __construct(
string $phql = null,
DiInterface $container = null,
array $options = []
);
Phalcon\Mvc\Model\Query constructor
cache()¶
Sets the cache parameters of the query
clean()¶
Destroys the internal PHQL cache
execute()¶
Executes a parsed PHQL statement
getBindParams()¶
Returns default bind params
getBindTypes()¶
Returns default bind types
getCache()¶
Returns the current cache backend instance
getCacheOptions()¶
Returns the current cache options
getDI()¶
Returns the dependency injection container
getIntermediate()¶
Returns the intermediate representation of the PHQL statement
getResultsetRowClass()¶
Returns the class that will be used to hydrate rows that are not mapped to a model (custom columns/joins). An empty string means the default Phalcon\Mvc\Model\Row is used.
getSingleResult()¶
Executes the query returning the first result
getSql()¶
Returns an associative array with the SQL to be generated by the internal PHQL, and arrays with bound parameters and their types (only works in SELECT statements).
[
'sql' => 'SELECT * FROM co_invoices WHERE inv_cst_id = :cst_id',
'bind' => ['cst_id' => 123],
'bindTypes => ['cst_id' => 1] // 1 corresponds to int
]
getTransaction()¶
getType()¶
Gets the type of PHQL statement executed
getUniqueRow()¶
Check if the query is programmed to get only the first row in the resultset
parse()¶
Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query
setBindParams()¶
Set default bind parameters
setBindTypes()¶
Set default bind parameters
setDI()¶
Sets the dependency injection container
setIntermediate()¶
Allows to set the IR to be executed
setResultsetRowClass()¶
Sets the class used to hydrate rows that are not mapped to a model (custom columns/joins). The class must be a subclass of Phalcon\Mvc\Model\Row.
setSharedLock()¶
Set SHARED LOCK clause
setTransaction()¶
allows to wrap a transaction around all queries
setType()¶
Sets the type of PHQL statement to be executed
setUniqueRow()¶
Tells to the query if only the first row in the resultset must be returned
executeDelete()¶
final protected function executeDelete(
array $intermediate,
array $bindParams,
array $bindTypes
): StatusInterface;
Executes the DELETE intermediate representation producing a Phalcon\Mvc\Model\Query\Status
executeInsert()¶
final protected function executeInsert(
array $intermediate,
array $bindParams,
array $bindTypes
): StatusInterface;
Executes the INSERT intermediate representation producing a Phalcon\Mvc\Model\Query\Status
executeSelect()¶
final protected function executeSelect(
array $intermediate,
array $bindParams,
array $bindTypes,
bool $simulate = false
): ResultsetInterface|array;
Executes the SELECT intermediate representation producing a Phalcon\Mvc\Model\Resultset
executeUpdate()¶
final protected function executeUpdate(
array $intermediate,
array $bindParams,
array $bindTypes
): StatusInterface;
Executes the UPDATE intermediate representation producing a Phalcon\Mvc\Model\Query\Status
getCallArgument()¶
Resolves an expression in a single call argument
getCaseExpression()¶
Resolves an expression in a single call argument
getExpression()¶
Resolves an expression from its intermediate code into an array
getFunctionCall()¶
Resolves an expression in a single call argument
getGroupClause()¶
Returns a processed group clause for a SELECT statement
getJoin()¶
Resolves a JOIN clause checking if the associated models exist
getJoinType()¶
Resolves a JOIN type
getJoins()¶
Processes the JOINs in the query returning an internal representation for the database dialect
getLimitClause()¶
Returns a processed limit clause for a SELECT statement
getMultiJoin()¶
final protected function getMultiJoin(
string $joinType,
mixed $joinSource,
string $modelAlias,
string $joinAlias,
RelationInterface $relation
): array;
Resolves joins involving many-to-many relations
getOrderClause()¶
Returns a processed order clause for a SELECT statement
getQualified()¶
Replaces the model's name to its source name in a qualified-name expression
getReadConnection()¶
protected function getReadConnection(
ModelInterface $model,
array $intermediate = null,
array $bindParams = [],
array $bindTypes = []
): AdapterInterface;
Gets the read connection from the model if there is no transaction set inside the query object
getRelatedRecords()¶
final protected function getRelatedRecords(
ModelInterface $model,
array $intermediate,
array $bindParams,
array $bindTypes
): ResultsetInterface;
Query the records on which the UPDATE/DELETE operation will be done
getSelectColumn()¶
Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complex
getSingleJoin()¶
final protected function getSingleJoin(
string $joinType,
mixed $joinSource,
string $modelAlias,
string $joinAlias,
RelationInterface $relation
): array;
Resolves joins involving has-one/belongs-to/has-many relations
getTable()¶
Resolves a table in a SELECT statement checking if the model exists
getWriteConnection()¶
protected function getWriteConnection(
ModelInterface $model,
array $intermediate = null,
array $bindParams = [],
array $bindTypes = []
): AdapterInterface;
Gets the write connection from the model if there is no transaction inside the query object
prepareDelete()¶
Analyzes a DELETE intermediate code and produces an array to be executed later
prepareInsert()¶
Analyzes an INSERT intermediate code and produces an array to be executed later
prepareSelect()¶
Analyzes a SELECT intermediate code and produces an array to be executed later
prepareUpdate()¶
Analyzes an UPDATE intermediate code and produces an array to be executed later
refreshSchemasInIntermediate()¶
Refreshes the schema/source of every model referenced in a cached intermediate representation. The PHQL cache is keyed by the PHQL string only, so a model that switches its schema or source at runtime (for instance via setSchema()/setSource() in initialize()) would otherwise see the value frozen at first parse. See #17020.
Mvc\Model\QueryInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\QueryInterface
Interface for Phalcon\Mvc\Model\Query
Phalcon\Mvc\Model\QueryInterface
Uses Phalcon\Mvc\ModelInterface
Method Summary¶
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
Methods¶
cache()¶
Sets the cache parameters of the query
execute()¶
Executes a parsed PHQL statement
getBindParams()¶
Returns default bind params
getBindTypes()¶
Returns default bind types
getCacheOptions()¶
Returns the current cache options
getSingleResult()¶
Executes the query returning the first result
getSql()¶
Returns the SQL to be generated by the internal PHQL (only works in SELECT statements)
getUniqueRow()¶
Check if the query is programmed to get only the first row in the resultset
parse()¶
Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query
setBindParams()¶
Set default bind parameters
setBindTypes()¶
Set default bind parameters
setSharedLock()¶
Set SHARED LOCK clause
setUniqueRow()¶
Tells to the query if only the first row in the resultset must be returned
Mvc\Model\Query\Builder¶
Class Source on GitHub
Helps to create PHQL queries using an OO interface
$params = [
"models" => [
Users::class,
],
"columns" => ["id", "name", "status"],
"conditions" => [
[
"created > :min: AND created < :max:",
[
"min" => "2013-01-01",
"max" => "2014-01-01",
],
[
"min" => PDO::PARAM_STR,
"max" => PDO::PARAM_STR,
],
],
],
// or "conditions" => "created > '2013-01-01' AND created < '2014-01-01'",
"group" => ["id", "name"],
"having" => "name = 'Kamil'",
"order" => ["name", "id"],
"limit" => 20,
"offset" => 20,
// or "limit" => [20, 20],
];
$queryBuilder = new \Phalcon\Mvc\Model\Query\Builder($params);
Phalcon\Mvc\Model\Query\Builder- implementsPhalcon\Mvc\Model\Query\BuilderInterface,Phalcon\Di\InjectionAwareInterface
Uses Phalcon\Db\Column · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\Model\Exception · Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable · Phalcon\Mvc\Model\QueryInterface · Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap · Phalcon\Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid · Phalcon\Mvc\Model\Query\Exceptions\Builder\ModelRequired · Phalcon\Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey · Phalcon\Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable · Phalcon\Support\Settings
Method Summary¶
public
__construct(mixed $params = null,DiInterface $container = null)
Phalcon\Mvc\Model\Query\Builder constructor
public
BuilderInterface
addFrom(string $model,string $alias = null)
Add a model to take part of the query
public
BuilderInterface
andHaving(string $conditions,array $bindParams = [],array $bindTypes = [])
Appends a condition to the current HAVING conditions clause using a AND operator
public
BuilderInterface
andWhere(string $conditions,array $bindParams = [],array $bindTypes = [])
Appends a condition to the current WHERE conditions using a AND operator
public
string
autoescape( string $identifier )
Automatically escapes identifiers but only if they need to be escaped.
public
BuilderInterface
betweenHaving(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND)
Appends a BETWEEN condition to the current HAVING conditions clause
public
BuilderInterface
betweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND)
Appends a BETWEEN condition to the current WHERE conditions
public
BuilderInterface
columns( mixed $columns )
Sets the columns to be queried. The columns can be either a string or
public
BuilderInterface
distinct( mixed $distinct )
Sets SELECT DISTINCT / SELECT ALL flag
public
BuilderInterface
forUpdate( bool $forUpdate )
Sets a FOR UPDATE clause
public
BuilderInterface
from( mixed $models )
Sets the models who makes part of the query
public
array
getBindParams()
Returns default bind params
public
array
getBindTypes()
Returns default bind types
public
getColumns()
Return the columns to be queried
public
DiInterface
getDI()
Returns the DependencyInjector container
public
bool
getDistinct()
Returns SELECT DISTINCT / SELECT ALL flag
public
getFrom()
Return the models who makes part of the query
public
array
getGroupBy()
Returns the GROUP BY clause
public
string|null
getHaving()
Return the current having clause
public
array
getJoins()
Return join parts of the query
public
getLimit()
Returns the current LIMIT clause
public
string|array|null
getModels()
Returns the models involved in the query
public
int
getOffset()
Returns the current OFFSET clause
public
getOrderBy()
Returns the set ORDER BY clause
public
string
getPhql()
Returns a PHQL statement built based on the builder parameters
public
QueryInterface
getQuery()
Returns the query built
public
string
getResultsetRowClass()
Returns the class that will be used to hydrate rows that are not mapped
public
getWhere()
Return the conditions for the query
public
BuilderInterface
groupBy( mixed $group )
Sets a GROUP BY clause
public
BuilderInterface
having(string $conditions,array $bindParams = [],array $bindTypes = [])
Sets the HAVING condition clause
public
BuilderInterface
inHaving(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND)
Appends an IN condition to the current HAVING conditions clause
public
BuilderInterface
inWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND)
Appends an IN condition to the current WHERE conditions
public
BuilderInterface
innerJoin(string $model,string $conditions = null,string $alias = null)
Adds an INNER join to the query
public
BuilderInterface
join(string $model,string $conditions = null,string $alias = null,string $type = null)
Adds an :type: join (by default type - INNER) to the query
public
BuilderInterface
leftJoin(string $model,string $conditions = null,string $alias = null)
Adds a LEFT join to the query
public
BuilderInterface
limit(int $limit,mixed $offset = null)
Sets a LIMIT clause, optionally an offset clause
public
BuilderInterface
notBetweenHaving(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND)
Appends a NOT BETWEEN condition to the current HAVING conditions clause
public
BuilderInterface
notBetweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND)
Appends a NOT BETWEEN condition to the current WHERE conditions
public
BuilderInterface
notInHaving(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND)
Appends a NOT IN condition to the current HAVING conditions clause
public
BuilderInterface
notInWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND)
Appends a NOT IN condition to the current WHERE conditions
public
BuilderInterface
offset( int $offset )
Sets an OFFSET clause
public
BuilderInterface
orHaving(string $conditions,array $bindParams = [],array $bindTypes = [])
Appends a condition to the current HAVING conditions clause using an OR operator
public
BuilderInterface
orWhere(string $conditions,array $bindParams = [],array $bindTypes = [])
Appends a condition to the current conditions using an OR operator
public
BuilderInterface
orderBy( mixed $orderBy )
Sets an ORDER BY condition clause
public
BuilderInterface
rightJoin(string $model,string $conditions = null,string $alias = null)
Adds a RIGHT join to the query
public
BuilderInterface
setBindParams(array $bindParams,bool $merge = false)
Set default bind parameters
public
BuilderInterface
setBindTypes(array $bindTypes,bool $merge = false)
Set default bind types
public
void
setDI( DiInterface $container )
Sets the DependencyInjector container
public
BuilderInterface
setResultsetRowClass( string $resultsetRowClass )
Sets the class used to hydrate rows that are not mapped to a model
public
BuilderInterface
where(string $conditions,array $bindParams = [],array $bindTypes = [])
Sets the query WHERE conditions
protected
BuilderInterface
conditionBetween(string $clause,string $operator,string $expr,mixed $minimum,mixed $maximum)
Appends a BETWEEN condition
protected
BuilderInterface
conditionIn(string $clause,string $operator,string $expr,array $values)
Appends an IN condition
protected
BuilderInterface
conditionNotBetween(string $clause,string $operator,string $expr,mixed $minimum,mixed $maximum)
Appends a NOT BETWEEN condition
protected
BuilderInterface
conditionNotIn(string $clause,string $operator,string $expr,array $values)
Appends a NOT IN condition
Properties¶
protected
array
$bindParams = []
protected
array
$bindTypes = []
protected
array|string|null
$columns = null
protected
array|string|null
$conditions = null
protected
DiInterface|null
$container
protected
mixed
$distinct = null
protected
bool
$forUpdate = false
protected
array
$group = []
protected
string|null
$having = null
protected
int
$hiddenParamNumber = 0
protected
array
$joins = []
protected
array|string
$limit
protected
array|string
$models
protected
int
$offset = 0
protected
array|string
$order
protected
string
$resultsetRowClass = ""
protected
bool
$sharedLock = false
Methods¶
__construct()¶
Phalcon\Mvc\Model\Query\Builder constructor
addFrom()¶
Add a model to take part of the query
// Load data from models Invoices
$builder->addFrom(
Invoices::class
);
// Load data from model 'Invoices' using 'r' as alias in PHQL
$builder->addFrom(
Invoices::class,
"r"
);
andHaving()¶
public function andHaving(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Appends a condition to the current HAVING conditions clause using a AND operator
$builder->andHaving("SUM(Invoices.inv_total) > 0");
$builder->andHaving(
"SUM(Invoices.inv_total) > :sum:",
[
"sum" => 100,
]
);
andWhere()¶
public function andWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Appends a condition to the current WHERE conditions using a AND operator
$builder->andWhere("name = 'Peter'");
$builder->andWhere(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
autoescape()¶
Automatically escapes identifiers but only if they need to be escaped.
betweenHaving()¶
public function betweenHaving(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a BETWEEN condition to the current HAVING conditions clause
betweenWhere()¶
public function betweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a BETWEEN condition to the current WHERE conditions
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
$builder->columns("id, category");
// Array, one column per element
$builder->columns(
[
"inv_id",
"inv_total",
]
);
// Array with named key. The name of the key acts as an
// alias (`AS` clause)
$builder->columns(
[
"inv_cst_id",
"total_invoices" => "COUNT(*)",
]
);
// Different models
$builder->columns(
[
"\Phalcon\Models\Invoices.*",
"\Phalcon\Models\Customers.cst_name_first",
"\Phalcon\Models\Customers.cst_name_last",
]
);
distinct()¶
Sets SELECT DISTINCT / SELECT ALL flag
forUpdate()¶
Sets a FOR UPDATE clause
from()¶
Sets the models who makes part of the query
$builder->from(
Invoices::class
);
$builder->from(
[
Invoices::class,
OrdersProducts::class,
]
);
$builder->from(
[
"r" => Invoices::class,
"rp" => OrdersProducts::class,
]
);
getBindParams()¶
Returns default bind params
getBindTypes()¶
Returns default bind types
getColumns()¶
Return the columns to be queried
getDI()¶
Returns the DependencyInjector container
getDistinct()¶
Returns SELECT DISTINCT / SELECT ALL flag
getFrom()¶
Return the models who makes part of the query
getGroupBy()¶
Returns the GROUP BY clause
getHaving()¶
Return the current having clause
getJoins()¶
Return join parts of the query
getLimit()¶
Returns the current LIMIT clause
getModels()¶
Returns the models involved in the query
getOffset()¶
Returns the current OFFSET clause
getOrderBy()¶
Returns the set ORDER BY clause
getPhql()¶
Returns a PHQL statement built based on the builder parameters
getQuery()¶
Returns the query built
getResultsetRowClass()¶
Returns the class that will be used to hydrate rows that are not mapped to a model (custom columns/joins). An empty string means the default Phalcon\Mvc\Model\Row is used.
getWhere()¶
Return the conditions for the query
groupBy()¶
Sets a GROUP BY clause
having()¶
public function having(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Sets the HAVING condition clause
$builder->having("SUM(Invoices.inv_total) > 0");
$builder->having(
"SUM(Invoices.inv_total) > :sum:",
[
"sum" => 100,
]
);
inHaving()¶
public function inHaving(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends an IN condition to the current HAVING conditions clause
inWhere()¶
public function inWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends an IN condition to the current WHERE conditions
innerJoin()¶
public function innerJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
Adds an INNER join to the query
// Inner Join model 'Invoices' with automatic conditions and alias
$builder->innerJoin(
Invoices::class
);
// Inner Join model 'Invoices' specifying conditions
$builder->innerJoin(
Invoices::class,
"Invoices.inv_id = OrdersProducts.oxp_ord_id"
);
// Inner Join model 'Invoices' specifying conditions and alias
$builder->innerJoin(
Invoices::class,
"r.inv_id = OrdersProducts.oxp_ord_id",
"r"
);
join()¶
public function join(
string $model,
string $conditions = null,
string $alias = null,
string $type = null
): BuilderInterface;
Adds an :type: join (by default type - INNER) to the query
// Inner Join model 'Invoices' with automatic conditions and alias
$builder->join(
Invoices::class
);
// Inner Join model 'Invoices' specifying conditions
$builder->join(
Invoices::class,
"Invoices.inv_id = OrdersProducts.oxp_ord_id"
);
// Inner Join model 'Invoices' specifying conditions and alias
$builder->join(
Invoices::class,
"r.inv_id = OrdersProducts.oxp_ord_id",
"r"
);
// Left Join model 'Invoices' specifying conditions, alias and type of join
$builder->join(
Invoices::class,
"r.inv_id = OrdersProducts.oxp_ord_id",
"r",
"LEFT"
);
leftJoin()¶
public function leftJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
Adds a LEFT join to the query
limit()¶
Sets a LIMIT clause, optionally an offset clause
notBetweenHaving()¶
public function notBetweenHaving(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT BETWEEN condition to the current HAVING conditions clause
notBetweenWhere()¶
public function notBetweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT BETWEEN condition to the current WHERE conditions
notInHaving()¶
public function notInHaving(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT IN condition to the current HAVING conditions clause
notInWhere()¶
public function notInWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT IN condition to the current WHERE conditions
offset()¶
Sets an OFFSET clause
orHaving()¶
public function orHaving(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Appends a condition to the current HAVING conditions clause using an OR operator
$builder->orHaving("SUM(Invoices.inv_total) > 0");
$builder->orHaving(
"SUM(Invoices.inv_total) > :sum:",
[
"sum" => 100,
]
);
orWhere()¶
public function orWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Appends a condition to the current conditions using an OR operator
$builder->orWhere("name = 'Peter'");
$builder->orWhere(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
orderBy()¶
Sets an ORDER BY condition clause
$builder->orderBy("Invoices.inv_title");
$builder->orderBy(["1", "Invoices.inv_title"]);
$builder->orderBy(["Invoices.inv_title DESC"]);
rightJoin()¶
public function rightJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
Adds a RIGHT join to the query
setBindParams()¶
Set default bind parameters
setBindTypes()¶
Set default bind types
setDI()¶
Sets the DependencyInjector container
setResultsetRowClass()¶
Sets the class used to hydrate rows that are not mapped to a model (custom columns/joins). The class must be a subclass of Phalcon\Mvc\Model\Row. Validation is performed by the underlying Phalcon\Mvc\Model\Query when the query is built.
where()¶
public function where(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Sets the query WHERE conditions
$builder->where(100);
$builder->where("name = 'Peter'");
$builder->where(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
conditionBetween()¶
protected function conditionBetween(
string $clause,
string $operator,
string $expr,
mixed $minimum,
mixed $maximum
): BuilderInterface;
Appends a BETWEEN condition
conditionIn()¶
protected function conditionIn(
string $clause,
string $operator,
string $expr,
array $values
): BuilderInterface;
Appends an IN condition
conditionNotBetween()¶
protected function conditionNotBetween(
string $clause,
string $operator,
string $expr,
mixed $minimum,
mixed $maximum
): BuilderInterface;
Appends a NOT BETWEEN condition
conditionNotIn()¶
protected function conditionNotIn(
string $clause,
string $operator,
string $expr,
array $values
): BuilderInterface;
Appends a NOT IN condition
Mvc\Model\Query\BuilderInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\Model\Query\Builder
Phalcon\Mvc\Model\Query\BuilderInterface
Uses Phalcon\Mvc\Model\QueryInterface
Method Summary¶
public
BuilderInterface
addFrom(string $model,string $alias = null)
Add a model to take part of the query
public
BuilderInterface
andWhere(string $conditions,array $bindParams = [],array $bindTypes = [])
Appends a condition to the current conditions using a AND operator
public
BuilderInterface
betweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND)
Appends a BETWEEN condition to the current conditions
public
BuilderInterface
columns( mixed $columns )
Sets the columns to be queried. The columns can be either a string or
public
BuilderInterface
distinct( mixed $distinct )
Sets SELECT DISTINCT / SELECT ALL flag
public
BuilderInterface
forUpdate( bool $forUpdate )
Sets a FOR UPDATE clause
public
BuilderInterface
from( mixed $models )
Sets the models who makes part of the query
public
array
getBindParams()
Returns default bind params
public
array
getBindTypes()
Returns default bind types
public
getColumns()
Return the columns to be queried
public
bool
getDistinct()
Returns SELECT DISTINCT / SELECT ALL flag
public
getFrom()
Return the models who makes part of the query
public
array
getGroupBy()
Returns the GROUP BY clause
public
string|null
getHaving()
Returns the HAVING condition clause
public
array
getJoins()
Return join parts of the query
public
getLimit()
Returns the current LIMIT clause
public
string|array|null
getModels()
Returns the models involved in the query
public
int
getOffset()
Returns the current OFFSET clause
public
getOrderBy()
Return the set ORDER BY clause
public
string
getPhql()
Returns a PHQL statement built based on the builder parameters
public
QueryInterface
getQuery()
Returns the query built
public
getWhere()
Return the conditions for the query
public
BuilderInterface
groupBy( mixed $group )
Sets a GROUP BY clause
public
BuilderInterface
having(string $conditions,array $bindParams = [],array $bindTypes = [])
Sets a HAVING condition clause
public
BuilderInterface
inWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND)
Appends an IN condition to the current conditions
public
BuilderInterface
innerJoin(string $model,string $conditions = null,string $alias = null)
Adds an INNER join to the query
public
BuilderInterface
join(string $model,string $conditions = null,string $alias = null)
Adds an :type: join (by default type - INNER) to the query
public
BuilderInterface
leftJoin(string $model,string $conditions = null,string $alias = null)
Adds a LEFT join to the query
public
BuilderInterface
limit(int $limit,mixed $offset = null)
Sets a LIMIT clause
public
BuilderInterface
notBetweenWhere(string $expr,mixed $minimum,mixed $maximum,string $operator = BuilderInterface::OPERATOR_AND)
Appends a NOT BETWEEN condition to the current conditions
public
BuilderInterface
notInWhere(string $expr,array $values,string $operator = BuilderInterface::OPERATOR_AND)
Appends a NOT IN condition to the current conditions
public
BuilderInterface
offset( int $offset )
Sets an OFFSET clause
public
BuilderInterface
orWhere(string $conditions,array $bindParams = [],array $bindTypes = [])
Appends a condition to the current conditions using an OR operator
public
BuilderInterface
orderBy( mixed $orderBy )
Sets an ORDER BY condition clause
public
BuilderInterface
rightJoin(string $model,string $conditions = null,string $alias = null)
Adds a RIGHT join to the query
public
BuilderInterface
setBindParams(array $bindParams,bool $merge = false)
Set default bind parameters
public
BuilderInterface
setBindTypes(array $bindTypes,bool $merge = false)
Set default bind types
public
BuilderInterface
where(string $conditions,array $bindParams = [],array $bindTypes = [])
Sets conditions for the query
Constants¶
string
OPERATOR_AND = "and"
string
OPERATOR_OR = "or"
Methods¶
addFrom()¶
Add a model to take part of the query
andWhere()¶
public function andWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Appends a condition to the current conditions using a AND operator
betweenWhere()¶
public function betweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a BETWEEN condition to the current conditions
columns()¶
Sets the columns to be queried. The columns can be either a string or
an array of strings. If the argument is a (single, non-embedded) string,
its content can specify one or more columns, separated by commas, the same
way that one uses the SQL select statement. You can use aliases, aggregate
functions, etc. If you need to reference other models you will need to
reference them with their namespaces.
When using an array as a parameter, you will need to specify one field per array element. If a non-numeric key is defined in the array, it will be used as the alias in the query
<?php
// String, comma separated values
$builder->columns("id, name");
// Array, one column per element
$builder->columns(
[
"id",
"name",
]
);
// Array, named keys. The name of the key acts as an alias (`AS` clause)
$builder->columns(
[
"name",
"number" => "COUNT(*)",
]
);
// Different models
$builder->columns(
[
"\Phalcon\Models\Invoices.*",
"\Phalcon\Models\Customers.cst_name_first",
"\Phalcon\Models\Customers.cst_name_last",
]
);
distinct()¶
Sets SELECT DISTINCT / SELECT ALL flag
forUpdate()¶
Sets a FOR UPDATE clause
from()¶
Sets the models who makes part of the query
getBindParams()¶
Returns default bind params
getBindTypes()¶
Returns default bind types
getColumns()¶
Return the columns to be queried
getDistinct()¶
Returns SELECT DISTINCT / SELECT ALL flag
getFrom()¶
Return the models who makes part of the query
getGroupBy()¶
Returns the GROUP BY clause
getHaving()¶
Returns the HAVING condition clause
getJoins()¶
Return join parts of the query
getLimit()¶
Returns the current LIMIT clause
getModels()¶
Returns the models involved in the query
getOffset()¶
Returns the current OFFSET clause
getOrderBy()¶
Return the set ORDER BY clause
getPhql()¶
Returns a PHQL statement built based on the builder parameters
getQuery()¶
Returns the query built
getWhere()¶
Return the conditions for the query
groupBy()¶
Sets a GROUP BY clause
having()¶
public function having(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Sets a HAVING condition clause
inWhere()¶
public function inWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends an IN condition to the current conditions
innerJoin()¶
public function innerJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
Adds an INNER join to the query
join()¶
public function join(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
Adds an :type: join (by default type - INNER) to the query
leftJoin()¶
public function leftJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
Adds a LEFT join to the query
limit()¶
Sets a LIMIT clause
notBetweenWhere()¶
public function notBetweenWhere(
string $expr,
mixed $minimum,
mixed $maximum,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT BETWEEN condition to the current conditions
notInWhere()¶
public function notInWhere(
string $expr,
array $values,
string $operator = BuilderInterface::OPERATOR_AND
): BuilderInterface;
Appends a NOT IN condition to the current conditions
offset()¶
Sets an OFFSET clause
orWhere()¶
public function orWhere(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Appends a condition to the current conditions using an OR operator
orderBy()¶
Sets an ORDER BY condition clause
rightJoin()¶
public function rightJoin(
string $model,
string $conditions = null,
string $alias = null
): BuilderInterface;
Adds a RIGHT join to the query
setBindParams()¶
Set default bind parameters
setBindTypes()¶
Set default bind types
where()¶
public function where(
string $conditions,
array $bindParams = [],
array $bindTypes = []
): BuilderInterface;
Sets conditions for the query
Mvc\Model\Query\Exceptions\AmbiguousColumn¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\AmbiguousColumn
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\AmbiguousJoinRelation¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\AmbiguousJoinRelation
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\BindParameterNotInPlaceholders
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\BindTypeRequiresArray¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\BindTypeRequiresArray
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\BindValueRequired¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\BindValueRequired
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\Builder\BuilderColumnNotInMap
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\Builder\BuilderConditionInvalid
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\Builder\ModelRequired¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\Builder\ModelRequired
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\Builder\NoPrimaryKey
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\Builder\OperatorNotAvailable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ColumnNotInDomain¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ColumnNotInDomain
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ColumnNotInSelectedModels
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\CorruptedAst¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\CorruptedAst
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\CorruptedDeleteAst¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\CorruptedDeleteAst
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\CorruptedInsertAst¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\CorruptedInsertAst
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\CorruptedSelectAst¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\CorruptedSelectAst
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\CorruptedUpdateAst¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\CorruptedUpdateAst
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\DeleteMultipleNotSupported
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\DuplicateAlias¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\DuplicateAlias
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\EmptyArrayPlaceholderValue
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InsertColumnCountMismatch¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InsertColumnCountMismatch
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidCachedResultset¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidCachedResultset
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidCachingOptions¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidCachingOptions
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidColumnDefinition¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidColumnDefinition
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidInjectedManager¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidInjectedManager
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidInjectedMetadata¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidInjectedMetadata
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidQueryCacheService¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidQueryCacheService
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidResultsetClass¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidResultsetClass
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\InvalidResultsetRowClass¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\InvalidResultsetRowClass
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\JoinAliasAlreadyUsed
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\JoinFieldCountMismatch¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\JoinFieldCountMismatch
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\MissingCacheKey¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\MissingCacheKey
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\MissingMetaData¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\MissingMetaData
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\MissingModelAttribute¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\MissingModelAttribute
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\MissingModelsManager¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\MissingModelsManager
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\MixedDatabaseSystems¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\MixedDatabaseSystems
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ModelSourceNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ModelSourceNotFound
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ModelsListNotLoaded¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ModelsListNotLoaded
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\MultipleSqlStatementsNotSupported
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\NoModelForAlias¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\NoModelForAlias
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\PhqlColumnNotInMap¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\PhqlColumnNotInMap
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ReadConnectionMissing¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ReadConnectionMissing
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\RelationshipNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\RelationshipNotFound
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ResultsetClassNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ResultsetClassNotFound
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ResultsetNonCacheable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ResultsetNonCacheable
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\ResultsetRowClassNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\ResultsetRowClassNotFound
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UnknownBindType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UnknownBindType
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UnknownColumnType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UnknownColumnType
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UnknownJoinType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UnknownJoinType
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UnknownModelOrAlias¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UnknownModelOrAlias
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UnknownPhqlExpression¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpression
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UnknownPhqlExpressionType
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UnknownPhqlStatement¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UnknownPhqlStatement
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\UpdateMultipleNotSupported
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Exceptions\WriteConnectionMissing¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Query\Exceptions\WriteConnectionMissing
Uses Phalcon\Mvc\Model\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Model\Query\Lang¶
Abstract Source on GitHub
Phalcon\Mvc\Model\Query\Lang
PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. It allows Phalcon to offer a unified SQL language to the developer, while internally doing all the work of translating PHQL instructions to the most optimal SQL instructions depending on the RDBMS type associated with a model.
To achieve the highest performance possible, we wrote a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe.
use Phalcon\Mvc\Model\Query\Lang;
$intermediate = Lang::parsePHQL(
"SELECT r.* FROM Invoices r LIMIT 10"
);
Phalcon\Mvc\Model\Query\Lang
Method Summary¶
Methods¶
parsePHQL()¶
Parses a PHQL statement returning an intermediate representation (IR)
Mvc\Model\Query\Status¶
Class Source on GitHub
This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails
$phql = "UPDATE Invoices SET inv_title = :inv_title:, inv_status_flag = :inv_status_flag:, inv_total = :inv_total: WHERE inv_id = :inv_id:";
$status = $app->modelsManager->executeQuery(
$phql,
[
"inv_id" => 100,
"inv_title" => "Test Invoice",
"inv_status_flag" => 1,
"inv_total" => 1959,
]
);
// Check if the update was successful
if ($status->success()) {
echo "OK";
}
Phalcon\Mvc\Model\Query\Status- implementsPhalcon\Mvc\Model\Query\StatusInterface
Uses Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface
Method Summary¶
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
Properties¶
protected
ModelInterface|null
$model
protected
bool
$success
Methods¶
__construct()¶
Phalcon\Mvc\Model\Query\Status
getMessages()¶
Returns the messages produced because of a failed operation
getModel()¶
Returns the model that executed the action
success()¶
Allows to check if the executed operation was successful
Mvc\Model\Query\StatusInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\Model\Query\Status
Phalcon\Mvc\Model\Query\StatusInterface
Uses Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface
Method Summary¶
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
Methods¶
getMessages()¶
Returns the messages produced by an operation failed
getModel()¶
Returns the model which executed the action
success()¶
Allows to check if the executed operation was successful
Mvc\Model\Relation¶
Class Source on GitHub
Phalcon\Mvc\Model\Relation
This class represents a relationship between two models
Phalcon\Mvc\Model\Relation- implementsPhalcon\Mvc\Model\RelationInterface
Method Summary¶
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
Constants¶
int
ACTION_CASCADE = 2
int
ACTION_RESTRICT = 1
int
BELONGS_TO = 0
int
HAS_MANY = 2
int
HAS_MANY_THROUGH = 4
int
HAS_ONE = 1
int
HAS_ONE_THROUGH = 3
int
NO_ACTION = 0
Properties¶
protected
array|string
$fields
protected
array|string
$intermediateFields
protected
string|null
$intermediateModel = null
protected
array|string
$intermediateReferencedFields
protected
array
$options = []
protected
array|string
$referencedFields
protected
string
$referencedModel
protected
int
$type
Methods¶
__construct()¶
public function __construct(
int $type,
string $referencedModel,
mixed $fields,
mixed $referencedFields,
array $options = []
);
Phalcon\Mvc\Model\Relation constructor
getFields()¶
Returns the fields
getForeignKey()¶
Returns the foreign key configuration
getIntermediateFields()¶
Gets the intermediate fields for has-*-through relations
getIntermediateModel()¶
Gets the intermediate model for has-*-through relations
getIntermediateReferencedFields()¶
Gets the intermediate referenced fields for has-*-through relations
getOption()¶
Returns an option by the specified name If the option does not exist null is returned
getOptions()¶
Returns the options
getParams()¶
Returns parameters that must be always used when the related records are obtained
getReferencedFields()¶
Returns the referenced fields
getReferencedModel()¶
Returns the referenced model
getType()¶
Returns the relation type
isForeignKey()¶
Check whether the relation act as a foreign key
isReusable()¶
Check if records returned by getting belongs-to/has-many are implicitly cached during the current request
isThrough()¶
Check whether the relation is a 'many-to-many' relation or not
setIntermediateRelation()¶
public function setIntermediateRelation(
mixed $intermediateFields,
string $intermediateModel,
mixed $intermediateReferencedFields
);
Sets the intermediate model data for has-*-through relations
Mvc\Model\RelationInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\RelationInterface
Interface for Phalcon\Mvc\Model\Relation
Phalcon\Mvc\Model\RelationInterface
Method Summary¶
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
Methods¶
getFields()¶
Returns the fields
getForeignKey()¶
Returns the foreign key configuration
getIntermediateFields()¶
Gets the intermediate fields for has-*-through relations
getIntermediateModel()¶
Gets the intermediate model for has-*-through relations
getIntermediateReferencedFields()¶
Gets the intermediate referenced fields for has-*-through relations
getOption()¶
Returns an option by the specified name If the option does not exist null is returned
getOptions()¶
Returns the options
getParams()¶
Returns parameters that must be always used when the related records are obtained
getReferencedFields()¶
Returns the referenced fields
getReferencedModel()¶
Returns the referenced model
getType()¶
Returns the relations type
isForeignKey()¶
Check whether the relation act as a foreign key
isReusable()¶
Check if records returned by getting belongs-to/has-many are implicitly cached during the current request
isThrough()¶
Check whether the relation is a 'many-to-many' relation or not
setIntermediateRelation()¶
public function setIntermediateRelation(
mixed $intermediateFields,
string $intermediateModel,
mixed $intermediateReferencedFields
);
Sets the intermediate model data for has-*-through relations
Mvc\Model\ResultInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\ResultInterface
All single objects passed as base objects to Resultsets must implement this interface
Phalcon\Mvc\Model\ResultInterface
Uses Phalcon\Mvc\ModelInterface
Method Summary¶
Methods¶
setDirtyState()¶
Sets the object's state
Mvc\Model\Resultset¶
Abstract Source on GitHub
Phalcon\Mvc\Model\Resultset
This component allows to Phalcon\Mvc\Model returns large resultsets with the minimum memory consumption Resultsets can be traversed using a standard foreach or a while statement. If a resultset is serialized it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before serializing.
// Using a standard foreach
$invoices = Invoices::find(
[
"inv_status_flag = 1",
"order" => "inv_title",
]
);
foreach ($invoices as invoice) {
echo invoice->inv_title, "\n";
}
// Using a while
$invoices = Invoices::find(
[
"inv_status_flag = 1",
"order" => "inv_title",
]
);
$invoices->rewind();
while ($invoices->valid()) {
$invoice = $invoices->current();
echo $invoice->inv_title, "\n";
$invoices->next();
}
Phalcon\Mvc\Model\Resultset- implementsPhalcon\Mvc\Model\ResultsetInterface,Iterator,SeekableIterator,Countable,ArrayAccess,JsonSerializable
Uses ArrayAccess · Closure · Countable · Iterator · JsonSerializable · Phalcon\Cache\CacheInterface · Phalcon\Db\Enum · Phalcon\Messages\MessageInterface · Phalcon\Mvc\Model · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Exceptions\CursorIsImmutable · Phalcon\Mvc\Model\Exceptions\IndexNotInCursor · Phalcon\Mvc\Model\Exceptions\InvalidResultsetCacheService · Phalcon\Mvc\Model\Exceptions\InvalidReturnedRecord · Phalcon\Storage\Serializer\SerializerInterface · Phalcon\Support\Settings · SeekableIterator
Method Summary¶
public
__construct(mixed $result,mixed $cache = null)
Phalcon\Mvc\Model\Resultset constructor
public
int
count()
Counts how many rows are in the resultset
public
bool
delete( Closure $conditionCallback = null )
Deletes every record in the resultset
public
ModelInterface[]
filter( callable $filter )
Filters a resultset returning only those the developer requires
public
CacheInterface|null
getCache()
Returns the associated cache for the resultset
public
mixed|null
getFirst()
Get first row in the resultset
public
int
getHydrateMode()
Returns the current hydration mode
public
ModelInterface|null
getLast()
Get last row in the resultset
public
MessageInterface[]
getMessages()
Returns the error messages produced by a batch operation
public
mixed
getResult()
public
int
getType()
Returns the internal type of data retrieval that the resultset is using
public
bool
isFresh()
Tell if the resultset if fresh or an old one cached
public
array
jsonSerialize()
Returns serialised model objects as array for json_encode.
public
int|null
key()
Gets pointer number of active row in the resultset
public
void
next()
Moves cursor to next row in the resultset
public
bool
offsetExists( mixed $index )
Checks whether offset exists in the resultset
public
mixed
offsetGet( mixed $index )
Gets row in a specific position of the resultset
public
void
offsetSet(mixed $offset,mixed $value)
Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
public
void
offsetUnset( mixed $offset )
Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
public
bool
refresh()
public
void
rewind()
Rewinds resultset to its beginning
public
void
seek( mixed $position )
Changes the internal pointer to a specific position in the resultset.
public
ResultsetInterface
setHydrateMode( int $hydrateMode )
Sets the hydration mode in the resultset
public
ResultsetInterface
setIsFresh( bool $isFresh )
Set if the resultset is fresh or an old one cached
public
bool
update(mixed $data,Closure $conditionCallback = null)
Updates every record in the resultset
public
bool
valid()
Check whether internal resource has rows to fetch
Constants¶
int
HYDRATE_ARRAYS = 1
int
HYDRATE_OBJECTS = 2
int
HYDRATE_RECORDS = 0
int
TYPE_RESULT_FULL = 0
int
TYPE_RESULT_PARTIAL = 1
Properties¶
protected
mixed|null
$activeRow = null
protected
CacheInterface|null
$cache = null
protected
int
$count = 0
protected
array
$errorMessages = []
protected
int
$hydrateMode = 0
protected
bool
$isFresh = true
protected
int
$pointer = 0
protected
ResultInterface|bool
$result
Phalcon\Db\ResultInterface or false for empty resultset
protected
mixed|null
$row = null
protected
array|null
$rows = null
Methods¶
__construct()¶
Phalcon\Mvc\Model\Resultset constructor
count()¶
Counts how many rows are in the resultset
delete()¶
Deletes every record in the resultset
filter()¶
Filters a resultset returning only those the developer requires
$filtered = $invoices->filter(
function ($invoice) {
if ($invoice->inv_id < 3) {
return $invoice;
}
}
);
getCache()¶
Returns the associated cache for the resultset
getFirst()¶
Get first row in the resultset
$model = new Invoices();
$manager = $model->getModelsManager();
// \Invoices
$manager->createQuery('SELECT * FROM Invoices')
->execute()
->getFirst();
// \Phalcon\Mvc\Model\Row
$manager->createQuery('SELECT r.inv_id FROM Invoices AS r')
->execute()
->getFirst();
// NULL
$manager->createQuery('SELECT r.inv_id FROM Invoices AS r WHERE r.inv_title = "NON-EXISTENT"')
->execute()
->getFirst();
getHydrateMode()¶
Returns the current hydration mode
getLast()¶
Get last row in the resultset
getMessages()¶
Returns the error messages produced by a batch operation
getResult()¶
getType()¶
Returns the internal type of data retrieval that the resultset is using
isFresh()¶
Tell if the resultset if fresh or an old one cached
jsonSerialize()¶
Returns serialised model objects as array for json_encode. Calls jsonSerialize on each object if present
key()¶
Gets pointer number of active row in the resultset
next()¶
Moves cursor to next row in the resultset
offsetExists()¶
Checks whether offset exists in the resultset
offsetGet()¶
Gets row in a specific position of the resultset
offsetSet()¶
Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
offsetUnset()¶
Resultsets cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
refresh()¶
rewind()¶
Rewinds resultset to its beginning
seek()¶
Changes the internal pointer to a specific position in the resultset. Set the new position if required, and then set this->row
setHydrateMode()¶
Sets the hydration mode in the resultset
setIsFresh()¶
Set if the resultset is fresh or an old one cached
update()¶
Updates every record in the resultset
valid()¶
Check whether internal resource has rows to fetch
Mvc\Model\ResultsetInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\ResultsetInterface
Interface for Phalcon\Mvc\Model\Resultset
Phalcon\Mvc\Model\ResultsetInterface
Uses Closure · Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface
Method Summary¶
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
Methods¶
delete()¶
Deletes every record in the resultset
filter()¶
Filters a resultset returning only those the developer requires
$filtered = $invoices->filter(
function ($invoice) {
if ($invoice->inv_id < 3) {
return $invoice;
}
}
);
getCache()¶
Returns the associated cache for the resultset
getFirst()¶
Get first row in the resultset
getHydrateMode()¶
Returns the current hydration mode
getLast()¶
Get last row in the resultset
getMessages()¶
Returns the error messages produced by a batch operation
getType()¶
Returns the internal type of data retrieval that the resultset is using
isFresh()¶
Tell if the resultset if fresh or an old one cached
setHydrateMode()¶
Sets the hydration mode in the resultset
setIsFresh()¶
Set if the resultset is fresh or an old one cached
toArray()¶
Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does.
update()¶
Updates every record in the resultset
Mvc\Model\Resultset\Complex¶
Class Source on GitHub
Phalcon\Mvc\Model\Resultset\Complex
Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required
@template TKey of int @template TValue of mixed
Phalcon\Mvc\Model\ResultsetPhalcon\Mvc\Model\Resultset\Complex
Uses Phalcon\Db\ResultInterface · Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Mvc\Model · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Exception · Phalcon\Mvc\Model\Exceptions\CorruptColumnType · Phalcon\Mvc\Model\Exceptions\InvalidContainer · Phalcon\Mvc\Model\Exceptions\InvalidSerializationData · Phalcon\Mvc\Model\Resultset · Phalcon\Mvc\Model\ResultsetInterface · Phalcon\Mvc\Model\Row · Phalcon\Storage\Serializer\SerializerInterface · Phalcon\Support\Settings · stdClass
Method Summary¶
public
__construct(mixed $columnTypes,ResultInterface $result = null,mixed $cache = null,string $resultsetRowClass = "")
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
Properties¶
protected
array
$columnTypes
protected
bool
$disableHydration = false
Unserialised result-set hydrated all rows already. unserialise() sets
disableHydration to true
protected
string
$resultsetRowClass = ""
Methods¶
__construct()¶
public function __construct(
mixed $columnTypes,
ResultInterface $result = null,
mixed $cache = null,
string $resultsetRowClass = ""
);
Phalcon\Mvc\Model\Resultset\Complex constructor
__serialize()¶
__unserialize()¶
current()¶
Returns current row in the resultset
serialize()¶
Serializing a resultset will dump all related rows into a big array, serialize it and return the resulting string
toArray()¶
Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does.
unserialize()¶
Unserializing a resultset will allow to only works on the rows present in the saved state
Mvc\Model\Resultset\Simple¶
Class Source on GitHub
Phalcon\Mvc\Model\Resultset\Simple
Simple resultsets only contains a complete objects This class builds every complete object as it is required
@template TKey of int @template TValue of \Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\ResultsetPhalcon\Mvc\Model\Resultset\Simple
Uses Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Mvc\Model · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Exception · Phalcon\Mvc\Model\Exceptions\InvalidContainer · Phalcon\Mvc\Model\Exceptions\InvalidSerializationData · Phalcon\Mvc\Model\Exceptions\ResultsetColumnNotInMap · Phalcon\Mvc\Model\Resultset · Phalcon\Mvc\Model\Row · Phalcon\Storage\Serializer\SerializerInterface · Phalcon\Support\Settings
Method Summary¶
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
Properties¶
protected
array|string
$columnMap
protected
bool
$keepSnapshots = false
protected
ModelInterface|Row
$model
Methods¶
__construct()¶
public function __construct(
mixed $columnMap,
mixed $model,
mixed $result,
mixed $cache = null,
bool $keepSnapshots = false
);
Phalcon\Mvc\Model\Resultset\Simple constructor
__serialize()¶
__unserialize()¶
current()¶
Returns current row in the resultset
serialize()¶
Serializing a resultset will dump all related rows into a big array
toArray()¶
Returns a complete resultset as an array, if the resultset has a big number of rows it could consume more memory than currently it does. Export the resultset to an array couldn't be faster with a large number of records
unserialize()¶
Unserializing a resultset will allow to only works on the rows present in the saved state
Mvc\Model\Row¶
Class Source on GitHub
This component allows Phalcon\Mvc\Model to return rows without an associated entity. This objects implements the ArrayAccess interface to allow access the object as object->x or array[x].
\stdClassPhalcon\Mvc\Model\Row- implementsPhalcon\Mvc\EntityInterface,Phalcon\Mvc\Model\ResultInterface,ArrayAccess,JsonSerializable
Uses ArrayAccess · JsonSerializable · Phalcon\Mvc\EntityInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Exceptions\IndexNotInRow · Phalcon\Mvc\Model\Exceptions\RowIsImmutable
Method Summary¶
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
Methods¶
jsonSerialize()¶
Serializes the object for json_encode
offsetExists()¶
Checks whether offset exists in the row. Returns true when the property is present on the row, regardless of whether its value is null - column presence is the contract, not value truthiness.
offsetGet()¶
Gets a record in a specific position of the row
offsetSet()¶
Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
offsetUnset()¶
Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface
readAttribute()¶
Reads an attribute value by its name
setDirtyState()¶
Set the current object's state
toArray()¶
Returns the instance as an array representation
writeAttribute()¶
Writes an attribute value by its name
Mvc\Model\Transaction¶
Class Source on GitHub
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Phalcon\Transaction is intended to be used with Phalcon_Model_Base. Phalcon Transactions should be created using Phalcon\Transaction\Manager.
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$manager = new Manager();
$transaction = $manager->get();
$invoice = new Invoices();
$invoice->setTransaction($transaction);
$invoice->inv_title = "Test Invoice";
$invoice->inv_created_at = date("Y-m-d");
if ($invoice->save() === false) {
$transaction->rollback("Can't save invoice");
}
$product = new Products();
$product->setTransaction($transaction);
$product->prd_name = "Widget";
if ($product->save() === false) {
$transaction->rollback("Can't save product");
}
$transaction->commit();
} catch(Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
Phalcon\Mvc\Model\Transaction- implementsPhalcon\Mvc\Model\TransactionInterface
Uses Phalcon\Db\Adapter\AdapterInterface · Phalcon\Di\DiInterface · Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\TransactionInterface · Phalcon\Mvc\Model\Transaction\Failed · Phalcon\Mvc\Model\Transaction\ManagerInterface
Method Summary¶
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
Properties¶
protected
bool
$activeTransaction = false
protected
AdapterInterface
$connection
protected
bool
$isNewTransaction = true
protected
ManagerInterface|null
$manager = null
protected
array
$messages = []
protected
bool
$rollbackOnAbort = false
protected
ModelInterface|null
$rollbackRecord = null
protected
bool
$rollbackThrowException = false
Methods¶
__construct()¶
public function __construct(
DiInterface $container,
bool $autoBegin = false,
string $service = "db"
);
Phalcon\Mvc\Model\Transaction constructor
begin()¶
Starts the transaction
commit()¶
Commits the transaction
getConnection()¶
Returns the connection related to transaction
getMessages()¶
Returns validations messages from last save try
isManaged()¶
Checks whether transaction is managed by a transaction manager
isValid()¶
Checks whether internal connection is under an active transaction
rollback()¶
public function rollback(
string $rollbackMessage = null,
ModelInterface $rollbackRecord = null
): bool;
Rollbacks the transaction
setIsNewTransaction()¶
Sets if is a reused transaction or new once
setRollbackOnAbort()¶
Sets flag to rollback on abort the HTTP connection
setRollbackedRecord()¶
Sets object which generates rollback action
setTransactionManager()¶
Sets transaction manager related to the transaction
throwRollbackException()¶
Enables throwing exception
Mvc\Model\TransactionInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\Model\Transaction
Phalcon\Mvc\Model\TransactionInterface
Uses Phalcon\Mvc\ModelInterface · Phalcon\Mvc\Model\Transaction\ManagerInterface
Method Summary¶
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
Methods¶
begin()¶
Starts the transaction
commit()¶
Commits the transaction
getConnection()¶
Returns connection related to transaction
getMessages()¶
Returns validations messages from last save try
isManaged()¶
Checks whether transaction is managed by a transaction manager
isValid()¶
Checks whether internal connection is under an active transaction
rollback()¶
public function rollback(
string $rollbackMessage = null,
ModelInterface $rollbackRecord = null
): bool;
Rollbacks the transaction
setIsNewTransaction()¶
Sets if is a reused transaction or new once
setRollbackOnAbort()¶
Sets flag to rollback on abort the HTTP connection
setRollbackedRecord()¶
Sets object which generates rollback action
setTransactionManager()¶
Sets transaction manager related to the transaction
throwRollbackException()¶
Enables throwing exception
Mvc\Model\Transaction\Exception¶
Class Source on GitHub
Phalcon\Mvc\Model\Transaction\Exception
Exceptions thrown in Phalcon\Mvc\Model\Transaction will use this class
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Transaction\Exception
Mvc\Model\Transaction\Failed¶
Class Source on GitHub
Phalcon\Mvc\Model\Transaction\Failed
This class will be thrown to exit a try/catch block for isolated transactions
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\Transaction\ExceptionPhalcon\Mvc\Model\Transaction\Failed
Uses Phalcon\Messages\MessageInterface · Phalcon\Mvc\ModelInterface
Method Summary¶
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
Properties¶
protected
ModelInterface|null
$record = null
Methods¶
__construct()¶
Phalcon\Mvc\Model\Transaction\Failed constructor
getRecord()¶
Returns validation record messages which stop the transaction
getRecordMessages()¶
Returns validation record messages which stop the transaction
Mvc\Model\Transaction\Manager¶
Class Source on GitHub
A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them.
This class manages the objects that compose a transaction. A transaction produces a unique connection that is passed to every object part of the transaction.
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$transactionManager = new Manager();
$transaction = $transactionManager->get();
$invoice = new Invoices();
$invoice->setTransaction($transaction);
$invoice->inv_title = "Test Invoice";
$invoice->inv_created_at = date("Y-m-d");
if ($invoice->save() === false) {
$transaction->rollback("Can't save invoice");
}
$product = new Products();
$product->setTransaction($transaction);
$product->prd_name = "Widget";
if ($product->save() === false) {
$transaction->rollback("Can't save product");
}
$transaction->commit();
} catch (Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
Phalcon\Mvc\Model\Transaction\Manager- implementsPhalcon\Mvc\Model\Transaction\ManagerInterface,Phalcon\Di\InjectionAwareInterface
Uses Phalcon\Di\Di · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\Model\Exceptions\ManagerOrmServicesUnavailable · Phalcon\Mvc\Model\Transaction · Phalcon\Mvc\Model\TransactionInterface
Method Summary¶
public
__construct( DiInterface $container = null )
Phalcon\Mvc\Model\Transaction\Manager constructor
public
void
collectTransactions()
Remove all the transactions from the manager
public
commit()
Commits active transactions within the manager
public
TransactionInterface
get( bool $autoBegin = true )
Returns a new \Phalcon\Mvc\Model\Transaction or an already created once
public
DiInterface
getDI()
Returns the dependency injection container
public
string
getDbService()
Returns the database service used to isolate the transaction
public
TransactionInterface
getOrCreateTransaction( bool $autoBegin = true )
Create/Returns a new transaction or an existing one
public
bool
getRollbackPendent()
Check if the transaction manager is registering a shutdown function to
public
bool
has()
Checks whether the manager has an active transaction
public
void
notifyCommit( TransactionInterface $transaction )
Notifies the manager about a committed transaction
public
void
notifyRollback( TransactionInterface $transaction )
Notifies the manager about a rollbacked transaction
public
void
rollback( bool $collect = true )
Rollbacks active transactions within the manager
public
void
rollbackPendent()
Rollbacks active transactions within the manager
public
void
setDI( DiInterface $container )
Sets the dependency injection container
public
ManagerInterface
setDbService( string $service )
Sets the database service used to run the isolated transactions
public
ManagerInterface
setRollbackPendent( bool $rollbackPendent )
Set if the transaction manager must register a shutdown function to clean
protected
void
collectTransaction( TransactionInterface $transaction )
Removes transactions from the TransactionManager
Properties¶
protected
DiInterface|null
$container
protected
bool
$initialized = false
protected
int
$number = 0
protected
bool
$rollbackPendent = true
protected
string
$service = "db"
protected
array
$transactions = []
Methods¶
__construct()¶
Phalcon\Mvc\Model\Transaction\Manager constructor
collectTransactions()¶
Remove all the transactions from the manager
commit()¶
Commits active transactions within the manager
get()¶
Returns a new \Phalcon\Mvc\Model\Transaction or an already created once This method registers a shutdown function to rollback active connections
getDI()¶
Returns the dependency injection container
getDbService()¶
Returns the database service used to isolate the transaction
getOrCreateTransaction()¶
Create/Returns a new transaction or an existing one
getRollbackPendent()¶
Check if the transaction manager is registering a shutdown function to clean up pendent transactions
has()¶
Checks whether the manager has an active transaction
notifyCommit()¶
Notifies the manager about a committed transaction
notifyRollback()¶
Notifies the manager about a rollbacked transaction
rollback()¶
Rollbacks active transactions within the manager Collect will remove the transaction from the manager
rollbackPendent()¶
Rollbacks active transactions within the manager
setDI()¶
Sets the dependency injection container
setDbService()¶
Sets the database service used to run the isolated transactions
setRollbackPendent()¶
Set if the transaction manager must register a shutdown function to clean up pendent transactions
collectTransaction()¶
Removes transactions from the TransactionManager
Mvc\Model\Transaction\ManagerInterface¶
Interface Source on GitHub
Phalcon\Mvc\Model\Transaction\ManagerInterface
Interface for Phalcon\Mvc\Model\Transaction\Manager
Phalcon\Mvc\Model\Transaction\ManagerInterface
Uses Phalcon\Mvc\Model\TransactionInterface
Method Summary¶
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
Methods¶
collectTransactions()¶
Remove all the transactions from the manager
commit()¶
Commits active transactions within the manager
get()¶
Returns a new \Phalcon\Mvc\Model\Transaction or an already created once
getDbService()¶
Returns the database service used to isolate the transaction
getRollbackPendent()¶
Check if the transaction manager is registering a shutdown function to clean up pendent transactions
has()¶
Checks whether manager has an active transaction
notifyCommit()¶
Notifies the manager about a committed transaction
notifyRollback()¶
Notifies the manager about a rollbacked transaction
rollback()¶
Rollbacks active transactions within the manager Collect will remove transaction from the manager
rollbackPendent()¶
Rollbacks active transactions within the manager
setDbService()¶
Sets the database service used to run the isolated transactions
setRollbackPendent()¶
Set if the transaction manager must register a shutdown function to clean up pendent transactions
Mvc\Model\ValidationFailed¶
Class Source on GitHub
Phalcon\Mvc\Model\ValidationFailed
This exception is generated when a model fails to save a record Phalcon\Mvc\Model must be set up to have this behavior
\ExceptionPhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\ValidationFailed
Uses Phalcon\Messages\Message · Phalcon\Mvc\ModelInterface
Method Summary¶
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
Properties¶
protected
ModelInterface
$model
protected
array
$validationMessages = []
Methods¶
__construct()¶
Phalcon\Mvc\Model\ValidationFailed constructor
getMessages()¶
Returns the complete group of messages produced in the validation
getModel()¶
Returns the model that generated the messages
Mvc\ModuleDefinitionInterface¶
Interface Source on GitHub
This interface must be implemented by class module definitions
Phalcon\Mvc\ModuleDefinitionInterface
Uses Phalcon\Di\DiInterface
Method Summary¶
public
registerAutoloaders( DiInterface $container = null )
Registers an autoloader related to the module
public
registerServices( DiInterface $container )
Registers services related to the module
Methods¶
registerAutoloaders()¶
Registers an autoloader related to the module
registerServices()¶
Registers services related to the module
Mvc\Router¶
Class Source on GitHub
Phalcon\Mvc\Router
Phalcon\Mvc\Router is the standard framework router. Routing is the process of taking a URI endpoint (that part of the URI which comes after the base URL) and decomposing it into parameters to determine which module, controller, and action of that controller should receive the request
use Phalcon\Mvc\Router;
$router = new Router();
$router->add(
"/documentation/{chapter}/{name}\.{type:[a-z]+}",
[
"controller" => "documentation",
"action" => "show",
]
);
$router->handle(
"/documentation/1/examples.html"
);
echo $router->getControllerName();
stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Mvc\Router- implementsPhalcon\Mvc\RouterInterface,Phalcon\Events\EventsAwareInterface
Uses Phalcon\Cache\Adapter\AdapterInterface · Phalcon\Config\ConfigInterface · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Http\RequestInterface · Phalcon\Mvc\Router\Exception · Phalcon\Mvc\Router\Exceptions\BeforeMatchNotCallable · Phalcon\Mvc\Router\Exceptions\ConfigKeyMustBeArray · Phalcon\Mvc\Router\Exceptions\EmptyGroupOfRoutes · Phalcon\Mvc\Router\Exceptions\GroupRoutesMustBeArray · Phalcon\Mvc\Router\Exceptions\InvalidConfigSource · Phalcon\Mvc\Router\Exceptions\InvalidNotFoundPaths · Phalcon\Mvc\Router\Exceptions\InvalidRoutePosition · Phalcon\Mvc\Router\Exceptions\MissingGroupRouteKey · Phalcon\Mvc\Router\Exceptions\MissingRouteConfigKey · Phalcon\Mvc\Router\Exceptions\RequestServiceUnavailable · Phalcon\Mvc\Router\Exceptions\UnknownHttpMethod · Phalcon\Mvc\Router\Exceptions\WrongPathsKey · Phalcon\Mvc\Router\Group · Phalcon\Mvc\Router\GroupInterface · Phalcon\Mvc\Router\Route · Phalcon\Mvc\Router\RouteInterface · Phalcon\Traits\Php\FileTrait
Method Summary¶
public
__construct( bool $defaultRoutes = true )
Phalcon\Mvc\Router constructor
public
RouteInterface
add(string $pattern,mixed $paths = null,mixed $httpMethods = null,int $position = Router::POSITION_LAST)
Adds a route to the router without any HTTP constraint
public
RouteInterface
addConnect(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is CONNECT
public
RouteInterface
addDelete(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is DELETE
public
RouteInterface
addGet(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is GET
public
RouteInterface
addHead(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is HEAD
public
RouteInterface
addOptions(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Add a route to the router that only match if the HTTP method is OPTIONS
public
RouteInterface
addPatch(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is PATCH
public
RouteInterface
addPost(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is POST
public
RouteInterface
addPurge(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is PURGE
public
RouteInterface
addPut(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is PUT
public
RouteInterface
addTrace(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is TRACE
public
static
attach(RouteInterface $route,int $position = Router::POSITION_LAST)
Attach Route object to the routes stack.
public
array
buildDispatcherDump()
Produces a pure-data array describing every piece of state needed
public
void
clear()
Removes all the pre-defined routes
public
void
dumpDispatcher( string $path )
File-shaped helper around buildDispatcherDump(). Writes the dump as
public
string
getActionName()
Returns the processed action name
public
string
getControllerName()
Returns the processed controller name
public
array
getDefaults()
Returns an array of default parameters
public
ManagerInterface|null
getEventsManager()
Returns the internal event manager
public
array
getKeyRouteIds()
public
array
getKeyRouteNames()
public
RouteInterface|null
getMatchedRoute()
Returns the route that matches the handled URI
public
array
getMatches()
Returns the sub expressions in the regular expression matched
public
array
getMethodRoutes()
Returns the routes indexed by HTTP method.
public
string
getModuleName()
Returns the processed module name
public
string
getNamespaceName()
Returns the processed namespace name
public
array
getParams()
Returns the processed parameters
public
string
getRewriteUri()
Get rewrite info. This info is read from $_GET["_url"].
public
RouteInterface|bool
getRouteById( mixed $routeId )
Returns a route object by its id
public
RouteInterface|bool
getRouteByName( string $name )
Returns a route object by its name
public
RouteInterface[]
getRoutes()
Returns all the routes defined in the router
public
void
handle( string $uri )
Handles routing information received from the rewrite engine
public
bool
isExactControllerName()
Returns whether controller name should not be mangled
public
void
loadDispatcher( string $path )
File-shaped helper around loadDispatcherFromArray(). Includes the
public
void
loadDispatcherFromArray( array $dump )
Inverse of buildDispatcherDump(). Reconstructs every Route from the
public
static
loadFromConfig( mixed $config )
Loads routes from an array or Phalcon\Config\Config instance.
public
static
mount( GroupInterface $group )
Mounts a group of routes in the router
public
static
notFound( mixed $paths )
Set a group of paths to be returned when none of the defined routes are
public
static
removeExtraSlashes( bool $remove )
Set whether router must remove the extra slashes in the handled routes
public
static
setDefaultAction( string $actionName )
Sets the default action name
public
static
setDefaultController( string $controllerName )
Sets the default controller name
public
static
setDefaultModule( string $moduleName )
Sets the name of the default module
public
static
setDefaultNamespace( string $namespaceName )
Sets the name of the default namespace
public
static
setDefaults( array $defaults )
Sets an array of default paths. If a route is missing a path the router
public
void
setEventsManager( ManagerInterface $eventsManager )
Sets the events manager
public
static
setKeyRouteIds( array $routeIds )
public
static
setKeyRouteNames( array $routeNames )
public
static
setUriSource( int $uriSource )
Sets the URI source. One of the URI_SOURCE_* constants
public
void
useCache(CacheAdapterInterface $cache,string $key = "phalcon.router.dispatcher")
Cache-instance convenience wrapper. On cache hit, restores the
public
bool
wasMatched()
Checks if the router matches any of the defined routes
protected
void
addRouteFromConfig( array $routeData )
Adds a single route from a config array entry. Used by loadFromConfig.
protected
string
extractRealUri( string $uri )
protected
void
mountGroupFromConfig( array $groupData )
Builds a Group from a config entry and mounts it. Used by loadFromConfig.
protected
void
rebuildMethodIndex()
Constants¶
int
POSITION_FIRST = 0
int
POSITION_LAST = 1
int
REGEX_CHUNK_SIZE = 10
Number of alternatives per combined-regex chunk. Empirically derived
(FastRoute uses ~10) - keeps each chunk below PCRE's optimizer cliff.
int
URI_SOURCE_GET_URL = 0
int
URI_SOURCE_SERVER_REQUEST_URI = 1
Properties¶
protected
string
$action = ""
protected
array
$candidatesByMethod = []
Pre-merged per-method candidate buckets in attach order. For each HTTP
method seen on any registered route, the bucket contains the
method-specific routes followed by the "*" (no-constraint) routes.
The "*" key itself holds only the no-constraint routes - used when the
request method has no specific bucket.
Built in rebuildMethodIndex(); consumed by handle() in reverse.
protected
array
$combinedRegexByMethod = []
Combined PCRE pattern per method bucket (chunked list of strings).
Each chunk uses (?|...) branch reset and (*:N) mark labels. Built
only when the bucket meets gating: no hostname routes; standard
pattern shape.
protected
array
$combinedRegexDisabled = []
Boolean per method bucket: true when the combined regex cannot be
built (hostname route present, exotic pattern shape, etc.).
protected
array
$combinedRegexMarkMap = []
Map from MARK label back to the route index in
candidatesByMethod[method]. One per chunk.
combinedRegexMarkMap[method][chunkIdx][markLabel] = routeIdx
protected
string
$controller = ""
protected
string
$defaultAction = ""
protected
string
$defaultController = ""
protected
string
$defaultModule = ""
protected
string
$defaultNamespace = ""
protected
array
$defaultParams = []
protected
ManagerInterface|null
$eventsManager
protected
array
$hostnameByMethod = []
Per-method buckets of routes with hostname constraints, grouped by
raw hostname string. Routes are referenced by their index into
candidatesByMethod[method]. Built in rebuildMethodIndex().
Shape: hostnameByMethod[method][hostname] = list of route indices.
protected
array
$hostnameLessByMethod = []
Per-method indices of routes without a hostname constraint, in
attach order.
Shape: hostnameLessByMethod[method] = list of route indices into
candidatesByMethod[method].
protected
array
$keyRouteIds = []
protected
array
$keyRouteNames = []
protected
RouteInterface|null
$matchedRoute = null
protected
array
$matches = []
protected
array
$methodRoutes = []
protected
bool
$methodRoutesDirty = true
protected
string
$module = ""
protected
string
$namespaceName = ""
protected
array|string|null
$notFoundPaths = null
protected
array
$params = []
protected
CacheAdapterInterface|null
$pendingCache = null
Lazy-write cache target set by useCache(). When non-null, handle()
writes buildDispatcherDump() to this cache after a successful
rebuild on cache miss, then clears the property to skip subsequent
writes.
protected
string
$pendingCacheKey = ""
protected
bool
$removeExtraSlashes = false
protected
array
$routeMeta = []
Single-source per-route metadata cache. One entry per route, keyed
by the route's intrinsic id. Replaces the previous per-method-bucket
replication of metadata arrays. Built once in rebuildMethodIndex().
Shape: routeMeta[routeId] = [
"pattern": string, // compiled pattern
"isRegex": bool,
"hostname": string|null,
"hostRegex": string|null,
"beforeMatch": callable|null
]
protected
array
$routes = []
protected
array
$staticByMethod = []
Static-route hash, populated by rebuildMethodIndex(). For each method
bucket (including "*"), maps URI => list of routes whose compiled
pattern is a literal string equal to that URI.
protected
array
$staticShadowedByMethod = []
Shadow-detection map. If staticShadowedByMethod[method][uri] is set,
the static URI in that bucket is shadowed by a later-attached regex
route - the fast path MUST NOT be used; fall through to the dynamic
loop so the regex wins (reverse-iteration semantics).
protected
int
$uriSource = self::URI_SOURCE_GET_URL
protected
bool
$wasMatched = false
Methods¶
__construct()¶
Phalcon\Mvc\Router constructor
add()¶
public function add(
string $pattern,
mixed $paths = null,
mixed $httpMethods = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router without any HTTP constraint
use Phalcon\Mvc\Router;
$router->add("/about", "About::index");
$router->add(
"/about",
"About::index",
["GET", "POST"]
);
$router->add(
"/about",
"About::index",
["GET", "POST"],
Router::POSITION_FIRST
);
addConnect()¶
public function addConnect(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is CONNECT
addDelete()¶
public function addDelete(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is DELETE
addGet()¶
public function addGet(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is GET
addHead()¶
public function addHead(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is HEAD
addOptions()¶
public function addOptions(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Add a route to the router that only match if the HTTP method is OPTIONS
addPatch()¶
public function addPatch(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PATCH
addPost()¶
public function addPost(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is POST
addPurge()¶
public function addPurge(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support)
addPut()¶
public function addPut(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PUT
addTrace()¶
public function addTrace(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is TRACE
attach()¶
Attach Route object to the routes stack.
use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Route;
class CustomRoute extends Route {
// ...
}
$router = new Router();
$router->attach(
new CustomRoute("/about", "About::index", ["GET", "HEAD"]),
Router::POSITION_FIRST
);
buildDispatcherDump()¶
Produces a pure-data array describing every piece of state needed to reconstruct this router. The returned array is var_export-able (no objects, no closures). Used by dumpDispatcher() and by Phalcon\Cache integration via useCache().
Throws when a route has a Closure beforeMatch or converter - those cannot be cached.
clear()¶
Removes all the pre-defined routes
dumpDispatcher()¶
File-shaped helper around buildDispatcherDump(). Writes the dump as
a <?php return [...]; file, atomically (temp + rename) so concurrent
dumps don't corrupt the result.
getActionName()¶
Returns the processed action name
getControllerName()¶
Returns the processed controller name
getDefaults()¶
Returns an array of default parameters
getEventsManager()¶
Returns the internal event manager
getKeyRouteIds()¶
getKeyRouteNames()¶
getMatchedRoute()¶
Returns the route that matches the handled URI
getMatches()¶
Returns the sub expressions in the regular expression matched
getMethodRoutes()¶
Returns the routes indexed by HTTP method. Routes with no HTTP constraint are stored under the "*" key.
getModuleName()¶
Returns the processed module name
getNamespaceName()¶
Returns the processed namespace name
getParams()¶
Returns the processed parameters
getRewriteUri()¶
Get rewrite info. This info is read from $_GET["_url"]. This returns '/' if the rewrite information cannot be read
getRouteById()¶
Returns a route object by its id
getRouteByName()¶
Returns a route object by its name
getRoutes()¶
Returns all the routes defined in the router
handle()¶
Handles routing information received from the rewrite engine
isExactControllerName()¶
Returns whether controller name should not be mangled
loadDispatcher()¶
File-shaped helper around loadDispatcherFromArray(). Includes the file (opcache-friendly) and forwards the return value.
loadDispatcherFromArray()¶
Inverse of buildDispatcherDump(). Reconstructs every Route from the
scalar routes entries (preserving subclass and routeId), restores
every index, and marks the indexes clean so handle() skips rebuild.
loadFromConfig()¶
Loads routes from an array or Phalcon\Config\Config instance.
$router->loadFromConfig(
[
'routes' => [
[
'method' => 'get',
'pattern' => '/users',
'paths' => 'Users::index',
],
],
]
);
mount()¶
Mounts a group of routes in the router
notFound()¶
Set a group of paths to be returned when none of the defined routes are matched
removeExtraSlashes()¶
Set whether router must remove the extra slashes in the handled routes
setDefaultAction()¶
Sets the default action name
setDefaultController()¶
Sets the default controller name
setDefaultModule()¶
Sets the name of the default module
setDefaultNamespace()¶
Sets the name of the default namespace
@parma string namespaceName
setDefaults()¶
Sets an array of default paths. If a route is missing a path the router will use the defined here. This method must not be used to set a 404 route
setEventsManager()¶
Sets the events manager
setKeyRouteIds()¶
setKeyRouteNames()¶
setUriSource()¶
Sets the URI source. One of the URI_SOURCE_* constants
useCache()¶
public function useCache(
CacheAdapterInterface $cache,
string $key = "phalcon.router.dispatcher"
): void;
Cache-instance convenience wrapper. On cache hit, restores the dispatcher immediately. On miss, defers cache population until the next handle() completes - at which point buildDispatcherDump() is written to the cache key.
wasMatched()¶
Checks if the router matches any of the defined routes
addRouteFromConfig()¶
Adds a single route from a config array entry. Used by loadFromConfig.
extractRealUri()¶
mountGroupFromConfig()¶
Builds a Group from a config entry and mounts it. Used by loadFromConfig.
rebuildMethodIndex()¶
Mvc\RouterInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\Router
Phalcon\Mvc\RouterInterface
Uses Phalcon\Mvc\Router\GroupInterface · Phalcon\Mvc\Router\RouteInterface
Method Summary¶
public
RouteInterface
add(string $pattern,mixed $paths = null,mixed $httpMethods = null,int $position = Router::POSITION_LAST)
Adds a route to the router on any HTTP method
public
RouteInterface
addConnect(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is CONNECT
public
RouteInterface
addDelete(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is DELETE
public
RouteInterface
addGet(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is GET
public
RouteInterface
addHead(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is HEAD
public
RouteInterface
addOptions(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Add a route to the router that only match if the HTTP method is OPTIONS
public
RouteInterface
addPatch(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is PATCH
public
RouteInterface
addPost(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is POST
public
RouteInterface
addPurge(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is PURGE
public
RouteInterface
addPut(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is PUT
public
RouteInterface
addTrace(string $pattern,mixed $paths = null,int $position = Router::POSITION_LAST)
Adds a route to the router that only match if the HTTP method is TRACE
public
RouterInterface
attach(RouteInterface $route,int $position = Router::POSITION_LAST)
Attach Route object to the routes stack.
public
void
clear()
Removes all the defined routes
public
string
getActionName()
Returns processed action name
public
string
getControllerName()
Returns processed controller name
public
RouteInterface|null
getMatchedRoute()
Returns the route that matches the handled URI
public
array
getMatches()
Return the sub expressions in the regular expression matched
public
string
getModuleName()
Returns processed module name
public
string
getNamespaceName()
Returns processed namespace name
public
array
getParams()
Returns processed extra params
public
RouteInterface|bool
getRouteById( mixed $routeId )
Returns a route object by its id
public
RouteInterface|bool
getRouteByName( string $name )
Returns a route object by its name
public
RouteInterface[]
getRoutes()
Return all the routes defined in the router
public
void
handle( string $uri )
Handles routing information received from the rewrite engine
public
RouterInterface
loadFromConfig( mixed $config )
Loads routes from an array or Phalcon\Config\Config instance.
public
RouterInterface
mount( GroupInterface $group )
Mounts a group of routes in the router
public
RouterInterface
setDefaultAction( string $actionName )
Sets the default action name
public
RouterInterface
setDefaultController( string $controllerName )
Sets the default controller name
public
RouterInterface
setDefaultModule( string $moduleName )
Sets the name of the default module
public
RouterInterface
setDefaults( array $defaults )
Sets an array of default paths
public
bool
wasMatched()
Check if the router matches any of the defined routes
Methods¶
add()¶
public function add(
string $pattern,
mixed $paths = null,
mixed $httpMethods = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router on any HTTP method
addConnect()¶
public function addConnect(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is CONNECT
addDelete()¶
public function addDelete(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is DELETE
addGet()¶
public function addGet(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is GET
addHead()¶
public function addHead(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is HEAD
addOptions()¶
public function addOptions(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Add a route to the router that only match if the HTTP method is OPTIONS
addPatch()¶
public function addPatch(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PATCH
addPost()¶
public function addPost(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is POST
addPurge()¶
public function addPurge(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PURGE (Squid and Varnish support)
addPut()¶
public function addPut(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is PUT
addTrace()¶
public function addTrace(
string $pattern,
mixed $paths = null,
int $position = Router::POSITION_LAST
): RouteInterface;
Adds a route to the router that only match if the HTTP method is TRACE
attach()¶
public function attach(
RouteInterface $route,
int $position = Router::POSITION_LAST
): RouterInterface;
Attach Route object to the routes stack.
clear()¶
Removes all the defined routes
getActionName()¶
Returns processed action name
getControllerName()¶
Returns processed controller name
getMatchedRoute()¶
Returns the route that matches the handled URI
getMatches()¶
Return the sub expressions in the regular expression matched
getModuleName()¶
Returns processed module name
getNamespaceName()¶
Returns processed namespace name
getParams()¶
Returns processed extra params
getRouteById()¶
Returns a route object by its id
getRouteByName()¶
Returns a route object by its name
getRoutes()¶
Return all the routes defined in the router
handle()¶
Handles routing information received from the rewrite engine
loadFromConfig()¶
Loads routes from an array or Phalcon\Config\Config instance.
mount()¶
Mounts a group of routes in the router
setDefaultAction()¶
Sets the default action name
setDefaultController()¶
Sets the default controller name
setDefaultModule()¶
Sets the name of the default module
setDefaults()¶
Sets an array of default paths
wasMatched()¶
Check if the router matches any of the defined routes
Mvc\Router\Annotations¶
Class Source on GitHub
Phalcon\Mvc\Router\Annotations
A router that reads routes annotations from classes/resources
use Phalcon\Mvc\Router\Annotations;
$di->setShared(
"router",
function() {
// Use the annotations router
$router = new Annotations(false);
// This will do the same as above but only if the handled uri starts with /invoices
$router->addResource("Invoices", "/invoices");
return $router;
}
);
stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Mvc\RouterPhalcon\Mvc\Router\Annotations
Uses Phalcon\Annotations\Annotation · Phalcon\Di\DiInterface · Phalcon\Mvc\Router · Phalcon\Mvc\Router\Exceptions\AnnotationsServiceUnavailable · Phalcon\Mvc\Router\Exceptions\InvalidCallbackParameter
Method Summary¶
public
static
addModuleResource(string $module,string $handler,string $prefix = null)
Adds a resource to the annotations handler
public
static
addResource(string $handler,string $prefix = null)
Adds a resource to the annotations handler
public
getActionPreformatCallback()
public
array
getResources()
Return the registered resources
public
void
handle( string $uri )
Produce the routing parameters from the rewrite information
public
void
processActionAnnotation(string $module,string $namespaceName,string $controller,string $action,Annotation $annotation)
Checks for annotations in the public methods of the controller
public
processControllerAnnotation(string $handler,Annotation $annotation)
Checks for annotations in the controller docblock
public
self
setActionPreformatCallback( mixed $callback = null )
Sets the action preformat callback
public
self
setActionSuffix( string $actionSuffix )
Changes the action method suffix
public
self
setControllerSuffix( string $controllerSuffix )
Changes the controller class suffix
Properties¶
protected
callable|string|null
$actionPreformatCallback = null
protected
string
$actionSuffix = "Action"
protected
string
$controllerSuffix = "Controller"
protected
array
$handlers = []
protected
string
$routePrefix = ""
Methods¶
addModuleResource()¶
public function addModuleResource(
string $module,
string $handler,
string $prefix = null
): static;
Adds a resource to the annotations handler A resource is a class that contains routing annotations The class is located in a module
addResource()¶
Adds a resource to the annotations handler A resource is a class that contains routing annotations
getActionPreformatCallback()¶
getResources()¶
Return the registered resources
handle()¶
Produce the routing parameters from the rewrite information
processActionAnnotation()¶
public function processActionAnnotation(
string $module,
string $namespaceName,
string $controller,
string $action,
Annotation $annotation
): void;
Checks for annotations in the public methods of the controller
processControllerAnnotation()¶
Checks for annotations in the controller docblock
setActionPreformatCallback()¶
Sets the action preformat callback $action here already without suffix 'Action'
// Array as callback
$annotationRouter->setActionPreformatCallback(
[
new Uncamelize(),
'__invoke'
]
);
// Function as callback
$annotationRouter->setActionPreformatCallback(
function ($action) {
return $action;
}
);
// String as callback
$annotationRouter->setActionPreformatCallback('strtolower');
// If empty method constructor called [null], sets uncamelize with - delimiter
$annotationRouter->setActionPreformatCallback();
setActionSuffix()¶
Changes the action method suffix
setControllerSuffix()¶
Changes the controller class suffix
Mvc\Router\Exception¶
Class Source on GitHub
Phalcon\Mvc\Router\Exception
Exceptions thrown in Phalcon\Mvc\Router will use this class
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\AnnotationsServiceUnavailablePhalcon\Mvc\Router\Exceptions\BeforeMatchNotCallablePhalcon\Mvc\Router\Exceptions\ConfigKeyMustBeArrayPhalcon\Mvc\Router\Exceptions\EmptyGroupOfRoutesPhalcon\Mvc\Router\Exceptions\GroupRoutesMustBeArrayPhalcon\Mvc\Router\Exceptions\InvalidCallbackParameterPhalcon\Mvc\Router\Exceptions\InvalidConfigSourcePhalcon\Mvc\Router\Exceptions\InvalidNotFoundPathsPhalcon\Mvc\Router\Exceptions\InvalidRoutePathsPhalcon\Mvc\Router\Exceptions\InvalidRoutePositionPhalcon\Mvc\Router\Exceptions\InvalidRouterFactoryConfigPhalcon\Mvc\Router\Exceptions\MissingGroupRouteKeyPhalcon\Mvc\Router\Exceptions\MissingRouteConfigKeyPhalcon\Mvc\Router\Exceptions\RequestServiceUnavailablePhalcon\Mvc\Router\Exceptions\UnknownHttpMethodPhalcon\Mvc\Router\Exceptions\WrongPathsKey
Mvc\Router\Exceptions\AnnotationsServiceUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\AnnotationsServiceUnavailable
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\BeforeMatchNotCallable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\BeforeMatchNotCallable
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\ConfigKeyMustBeArray¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\ConfigKeyMustBeArray
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\EmptyGroupOfRoutes¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\EmptyGroupOfRoutes
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\GroupRoutesMustBeArray¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\GroupRoutesMustBeArray
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\InvalidCallbackParameter¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\InvalidCallbackParameter
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\InvalidConfigSource¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\InvalidConfigSource
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\InvalidNotFoundPaths¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\InvalidNotFoundPaths
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\InvalidRoutePaths¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\InvalidRoutePaths
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\InvalidRoutePosition¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\InvalidRoutePosition
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\InvalidRouterFactoryConfig¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\InvalidRouterFactoryConfig
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\MissingGroupRouteKey¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\MissingGroupRouteKey
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\MissingRouteConfigKey¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\MissingRouteConfigKey
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\RequestServiceUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\RequestServiceUnavailable
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\UnknownHttpMethod¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\UnknownHttpMethod
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Exceptions\WrongPathsKey¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Router\ExceptionPhalcon\Mvc\Router\Exceptions\WrongPathsKey
Uses Phalcon\Mvc\Router\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Router\Group¶
Class Source on GitHub
Helper class to create a group of routes with common attributes
$router = new \Phalcon\Mvc\Router();
//Create a group with a common module and controller
$blog = new Group(
[
"module" => "blog",
"controller" => "index",
]
);
//All the routes start with /blog
$blog->setPrefix("/blog");
//Add a route to the group
$blog->add(
"/save",
[
"action" => "save",
]
);
//Add another route to the group
$blog->add(
"/edit/{id}",
[
"action" => "edit",
]
);
//This route maps to a controller different than the default
$blog->add(
"/blog",
[
"controller" => "about",
"action" => "index",
]
);
//Add the group to the router
$router->mount($blog);
Phalcon\Mvc\Router\Group- implementsPhalcon\Mvc\Router\GroupInterface
Method Summary¶
public
__construct( mixed $paths = null )
Phalcon\Mvc\Router\Group constructor
public
RouteInterface
add(string $pattern,mixed $paths = null,mixed $httpMethods = null)
Adds a route to the router on any HTTP method
public
RouteInterface
addConnect(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is CONNECT
public
RouteInterface
addDelete(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is DELETE
public
RouteInterface
addGet(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is GET
public
RouteInterface
addHead(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is HEAD
public
RouteInterface
addOptions(string $pattern,mixed $paths = null)
Add a route to the router that only match if the HTTP method is OPTIONS
public
RouteInterface
addPatch(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is PATCH
public
RouteInterface
addPost(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is POST
public
RouteInterface
addPurge(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is PURGE
public
RouteInterface
addPut(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is PUT
public
RouteInterface
addTrace(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is TRACE
public
GroupInterface
beforeMatch( callable $beforeMatch )
Sets a callback that is called if the route is matched.
public
void
clear()
Removes all the pre-defined routes
public
callable|null
getBeforeMatch()
Returns the 'before match' callback if any
public
string|null
getHostname()
Returns the hostname restriction
public
array|string|null
getPaths()
Returns the common paths defined for this group
public
string|null
getPrefix()
Returns the common prefix for all the routes
public
RouteInterface[]
getRoutes()
Returns the routes added to the group
public
GroupInterface
setHostname( string $hostname )
Set a hostname restriction for all the routes in the group
public
GroupInterface
setPaths( mixed $paths )
Set common paths for all the routes in the group
public
GroupInterface
setPrefix( string $prefix )
Set a common uri prefix for all the routes in this group
protected
RouteInterface
addRoute(string $pattern,mixed $paths = null,mixed $httpMethods = null)
Adds a route applying the common attributes
Properties¶
protected
callable|null
$beforeMatch = null
protected
string|null
$hostname = null
protected
array|string|null
$paths = null
protected
string|null
$prefix = null
protected
array
$routes = []
Methods¶
__construct()¶
Phalcon\Mvc\Router\Group constructor
add()¶
public function add(
string $pattern,
mixed $paths = null,
mixed $httpMethods = null
): RouteInterface;
Adds a route to the router on any HTTP method
addConnect()¶
Adds a route to the router that only match if the HTTP method is CONNECT
addDelete()¶
Adds a route to the router that only match if the HTTP method is DELETE
addGet()¶
Adds a route to the router that only match if the HTTP method is GET
addHead()¶
Adds a route to the router that only match if the HTTP method is HEAD
addOptions()¶
Add a route to the router that only match if the HTTP method is OPTIONS
addPatch()¶
Adds a route to the router that only match if the HTTP method is PATCH
addPost()¶
Adds a route to the router that only match if the HTTP method is POST
addPurge()¶
Adds a route to the router that only match if the HTTP method is PURGE
addPut()¶
Adds a route to the router that only match if the HTTP method is PUT
addTrace()¶
Adds a route to the router that only match if the HTTP method is TRACE
beforeMatch()¶
Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched
clear()¶
Removes all the pre-defined routes
getBeforeMatch()¶
Returns the 'before match' callback if any
getHostname()¶
Returns the hostname restriction
getPaths()¶
Returns the common paths defined for this group
getPrefix()¶
Returns the common prefix for all the routes
getRoutes()¶
Returns the routes added to the group
setHostname()¶
Set a hostname restriction for all the routes in the group
setPaths()¶
Set common paths for all the routes in the group
setPrefix()¶
Set a common uri prefix for all the routes in this group
addRoute()¶
protected function addRoute(
string $pattern,
mixed $paths = null,
mixed $httpMethods = null
): RouteInterface;
Adds a route applying the common attributes
Mvc\Router\GroupInterface¶
Interface Source on GitHub
$router = new \Phalcon\Mvc\Router();
// Create a group with a common module and controller
$blog = new Group(
[
"module" => "blog",
"controller" => "index",
]
);
// All the routes start with /blog
$blog->setPrefix("/blog");
// Add a route to the group
$blog->add(
"/save",
[
"action" => "save",
]
);
// Add another route to the group
$blog->add(
"/edit/{id}",
[
"action" => "edit",
]
);
// This route maps to a controller different than the default
$blog->add(
"/blog",
[
"controller" => "about",
"action" => "index",
]
);
// Add the group to the router
$router->mount($blog);
Phalcon\Mvc\Router\GroupInterface
Method Summary¶
public
RouteInterface
add(string $pattern,mixed $paths = null,mixed $httpMethods = null)
Adds a route to the router on any HTTP method
public
RouteInterface
addConnect(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is CONNECT
public
RouteInterface
addDelete(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is DELETE
public
RouteInterface
addGet(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is GET
public
RouteInterface
addHead(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is HEAD
public
RouteInterface
addOptions(string $pattern,mixed $paths = null)
Add a route to the router that only match if the HTTP method is OPTIONS
public
RouteInterface
addPatch(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is PATCH
public
RouteInterface
addPost(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is POST
public
RouteInterface
addPurge(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is PURGE
public
RouteInterface
addPut(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is PUT
public
RouteInterface
addTrace(string $pattern,mixed $paths = null)
Adds a route to the router that only match if the HTTP method is TRACE
public
GroupInterface
beforeMatch( callable $beforeMatch )
Sets a callback that is called if the route is matched.
public
void
clear()
Removes all the pre-defined routes
public
callable|null
getBeforeMatch()
Returns the 'before match' callback if any
public
string|null
getHostname()
Returns the hostname restriction
public
array|string|null
getPaths()
Returns the common paths defined for this group
public
string|null
getPrefix()
Returns the common prefix for all the routes
public
RouteInterface[]
getRoutes()
Returns the routes added to the group
public
GroupInterface
setHostname( string $hostname )
Set a hostname restriction for all the routes in the group
public
GroupInterface
setPaths( mixed $paths )
Set common paths for all the routes in the group
public
GroupInterface
setPrefix( string $prefix )
Set a common uri prefix for all the routes in this group
Methods¶
add()¶
public function add(
string $pattern,
mixed $paths = null,
mixed $httpMethods = null
): RouteInterface;
Adds a route to the router on any HTTP method
addConnect()¶
Adds a route to the router that only match if the HTTP method is CONNECT
addDelete()¶
Adds a route to the router that only match if the HTTP method is DELETE
addGet()¶
Adds a route to the router that only match if the HTTP method is GET
addHead()¶
Adds a route to the router that only match if the HTTP method is HEAD
addOptions()¶
Add a route to the router that only match if the HTTP method is OPTIONS
addPatch()¶
Adds a route to the router that only match if the HTTP method is PATCH
addPost()¶
Adds a route to the router that only match if the HTTP method is POST
addPurge()¶
Adds a route to the router that only match if the HTTP method is PURGE
addPut()¶
Adds a route to the router that only match if the HTTP method is PUT
addTrace()¶
Adds a route to the router that only match if the HTTP method is TRACE
beforeMatch()¶
Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched
clear()¶
Removes all the pre-defined routes
getBeforeMatch()¶
Returns the 'before match' callback if any
getHostname()¶
Returns the hostname restriction
getPaths()¶
Returns the common paths defined for this group
getPrefix()¶
Returns the common prefix for all the routes
getRoutes()¶
Returns the routes added to the group
setHostname()¶
Set a hostname restriction for all the routes in the group
setPaths()¶
Set common paths for all the routes in the group
setPrefix()¶
Set a common uri prefix for all the routes in this group
Mvc\Router\Route¶
Class Source on GitHub
This class represents every route added to the router
Phalcon\Mvc\Router\Route- implementsPhalcon\Mvc\Router\RouteInterface
Uses Phalcon\Mvc\Router\Exceptions\InvalidRoutePaths
Method Summary¶
public
__construct(string $pattern,mixed $paths = null,mixed $httpMethods = null)
Phalcon\Mvc\Router\Route constructor
public
RouteInterface
beforeMatch( callable $callback )
Sets a callback that is called if the route is matched.
public
string
compilePattern( string $pattern )
Replaces placeholders from pattern returning a valid PCRE regular expression
public
RouteInterface
convert(string $name,mixed $converter)
{@inheritdoc}
public
array|bool
extractNamedParams( string $pattern )
Extracts parameters from a string
public
callable|null
getBeforeMatch()
Returns the 'before match' callback if any
public
string|null
getCompiledHostName()
Returns the compiled hostname regex, or null when the hostname is
public
string
getCompiledPattern()
Returns the route's compiled pattern
public
array
getConverters()
Returns the router converter
public
GroupInterface|null
getGroup()
Returns the group associated with the route
public
string|null
getHostname()
Returns the hostname restriction if any
public
array|string|null
getHttpMethods()
Returns the HTTP methods that constraint matching the route
public
callable|null
getMatch()
Returns the 'match' callback if any
public
string|null
getName()
Returns the route's name
public
array
getPaths()
Returns the paths
public
string
getPattern()
Returns the route's pattern
public
array
getReversedPaths()
Returns the paths using positions as keys and names as values
public
string
getRouteId()
Returns the route's id
public
array
getRoutePaths( mixed $paths = null )
Returns routePaths
public
RouteInterface
match( mixed $callback )
Allows to set a callback to handle the request directly in the route
public
void
reConfigure(string $pattern,mixed $paths = null)
Reconfigure the route adding a new pattern and a set of paths
public
void
reset()
Resets the internal route id generator
public
RouteInterface
setGroup( GroupInterface $group )
Sets the group associated with the route
public
RouteInterface
setHostname( string $hostname )
Sets a hostname restriction to the route
public
RouteInterface
setHttpMethods( mixed $httpMethods )
Sets a set of HTTP methods that constraint the matching of the route (alias of via)
public
RouteInterface
setName( string $name )
Sets the route's name
public
RouteInterface
setRouteId( string $routeId )
Sets the route's id. Intended for restoring cached routes - most
public
RouteInterface
via( mixed $httpMethods )
Set one or more HTTP methods that constraint the matching of the route
Properties¶
protected
callable|null
$beforeMatch = null
protected
string|null|false
$compiledHostName = false
Cached compiled hostname regex. false means "not yet computed";
null means "hostname is literal - use string equality"; any string
means "use this as the PCRE pattern."
protected
string|null
$compiledPattern = null
protected
array
$converters = []
protected
GroupInterface|null
$group = null
protected
string|null
$hostname = null
protected
callable|null
$match = null
protected
array|string|null
$methods = []
protected
string|null
$name = null
protected
array
$paths = []
protected
string
$pattern
protected
string
$routeId = ""
protected
int
$uniqueId = 0
Methods¶
__construct()¶
Phalcon\Mvc\Router\Route constructor
beforeMatch()¶
Sets a callback that is called if the route is matched. The developer can implement any arbitrary conditions here If the callback returns false the route is treated as not matched
$router->add(
"/login",
[
"module" => "admin",
"controller" => "session",
]
)->beforeMatch(
function ($uri, $route) {
// Check if the request was made with Ajax
if ($_SERVER["HTTP_X_REQUESTED_WITH"] === "xmlhttprequest") {
return false;
}
return true;
}
);
compilePattern()¶
Replaces placeholders from pattern returning a valid PCRE regular expression
convert()¶
{@inheritdoc}
extractNamedParams()¶
Extracts parameters from a string
getBeforeMatch()¶
Returns the 'before match' callback if any
getCompiledHostName()¶
Returns the compiled hostname regex, or null when the hostname is literal and a string-equality comparison should be used.
The result is cached after first computation; setHostname() clears the cache.
getCompiledPattern()¶
Returns the route's compiled pattern
getConverters()¶
Returns the router converter
getGroup()¶
Returns the group associated with the route
getHostname()¶
Returns the hostname restriction if any
getHttpMethods()¶
Returns the HTTP methods that constraint matching the route
getMatch()¶
Returns the 'match' callback if any
getName()¶
Returns the route's name
getPaths()¶
Returns the paths
getPattern()¶
Returns the route's pattern
getReversedPaths()¶
Returns the paths using positions as keys and names as values
getRouteId()¶
Returns the route's id
getRoutePaths()¶
Returns routePaths
match()¶
Allows to set a callback to handle the request directly in the route
$router->add(
"/help",
[]
)->match(
function () {
return $this->getResponse()->redirect("https://support.google.com/", true);
}
);
reConfigure()¶
Reconfigure the route adding a new pattern and a set of paths
reset()¶
Resets the internal route id generator
setGroup()¶
Sets the group associated with the route
setHostname()¶
Sets a hostname restriction to the route
setHttpMethods()¶
Sets a set of HTTP methods that constraint the matching of the route (alias of via)
setName()¶
Sets the route's name
setRouteId()¶
Sets the route's id. Intended for restoring cached routes - most applications should rely on the auto-incrementing id assigned by the constructor.
via()¶
Set one or more HTTP methods that constraint the matching of the route
Mvc\Router\RouteInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\Router\Route
Phalcon\Mvc\Router\RouteInterface
Method Summary¶
public
string
compilePattern( string $pattern )
Replaces placeholders from pattern returning a valid PCRE regular expression
public
RouteInterface
convert(string $name,mixed $converter)
Adds a converter to perform an additional transformation for certain parameter.
public
string
getCompiledPattern()
Returns the route's pattern
public
string|null
getHostname()
Returns the hostname restriction if any
public
array|string|null
getHttpMethods()
Returns the HTTP methods that constraint matching the route
public
string|null
getName()
Returns the route's name
public
array
getPaths()
Returns the paths
public
string
getPattern()
Returns the route's pattern
public
array
getReversedPaths()
Returns the paths using positions as keys and names as values
public
string
getRouteId()
Returns the route's id
public
void
reConfigure(string $pattern,mixed $paths = null)
Reconfigure the route adding a new pattern and a set of paths
public
void
reset()
Resets the internal route id generator
public
RouteInterface
setHostname( string $hostname )
Sets a hostname restriction to the route
public
RouteInterface
setHttpMethods( mixed $httpMethods )
Sets a set of HTTP methods that constraint the matching of the route
public
RouteInterface
setName( string $name )
Sets the route's name
public
RouteInterface
setRouteId( string $routeId )
Sets the route's id (intended for restoring cached routes)
public
RouteInterface
via( mixed $httpMethods )
Set one or more HTTP methods that constraint the matching of the route
Methods¶
compilePattern()¶
Replaces placeholders from pattern returning a valid PCRE regular expression
convert()¶
Adds a converter to perform an additional transformation for certain parameter.
getCompiledPattern()¶
Returns the route's pattern
getHostname()¶
Returns the hostname restriction if any
getHttpMethods()¶
Returns the HTTP methods that constraint matching the route
getName()¶
Returns the route's name
getPaths()¶
Returns the paths
getPattern()¶
Returns the route's pattern
getReversedPaths()¶
Returns the paths using positions as keys and names as values
getRouteId()¶
Returns the route's id
reConfigure()¶
Reconfigure the route adding a new pattern and a set of paths
reset()¶
Resets the internal route id generator
setHostname()¶
Sets a hostname restriction to the route
setHttpMethods()¶
Sets a set of HTTP methods that constraint the matching of the route
setName()¶
Sets the route's name
setRouteId()¶
Sets the route's id (intended for restoring cached routes)
via()¶
Set one or more HTTP methods that constraint the matching of the route
Mvc\Router\RouterFactory¶
Class Source on GitHub
Phalcon\Mvc\Router\RouterFactory
Builds a Router from an array or ConfigInterface and loads routes via Router::loadFromConfig.
use Phalcon\Mvc\Router\RouterFactory;
$router = (new RouterFactory())->load(
[
"defaultRoutes" : false,
"routes" : [
["method" : "get", "pattern" : "/users", "paths" : "Users::index"]
]
]
);
Phalcon\Mvc\Router\RouterFactory
Uses Phalcon\Config\ConfigInterface · Phalcon\Mvc\Router · Phalcon\Mvc\RouterInterface · Phalcon\Mvc\Router\Exceptions\InvalidRouterFactoryConfig
Method Summary¶
public
RouterInterface
load( mixed $config )
Builds a Router from a config array or ConfigInterface and loads routes.
public
RouterInterface
newInstance( bool $defaultRoutes = true )
Returns a bare Router instance.
Methods¶
load()¶
Builds a Router from a config array or ConfigInterface and loads routes.
newInstance()¶
Returns a bare Router instance.
Mvc\Url¶
Class Source on GitHub
This component helps in the generation of: URIs, URLs and Paths
// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");
// Generate a URL for a predefined route
echo $url->get(
[
"for" => "blog-post",
"title" => "some-cool-stuff",
"year" => "2012",
]
);
stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Mvc\Url- implementsPhalcon\Mvc\Url\UrlInterface
Uses Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Mvc\RouterInterface · Phalcon\Mvc\Router\RouteInterface · Phalcon\Mvc\Url\Exception · Phalcon\Mvc\Url\Exceptions\MissingRouteName · Phalcon\Mvc\Url\Exceptions\RouteNotFound · Phalcon\Mvc\Url\Exceptions\RouterServiceUnavailable · Phalcon\Mvc\Url\UrlInterface · Phalcon\Support\Helper\Str\ReduceSlashes
Method Summary¶
public
__construct( RouterInterface $router = null )
public
string
get(mixed $uri = null,mixed $arguments = null,bool $local = null,mixed $baseUri = null,bool $replaceArgs = false)
Generates a URL
public
string|null
getBasePath()
Returns the base path
public
string
getBaseUri()
Returns the prefix for all the generated urls. By default /
public
string
getStatic( mixed $uri = null )
Generates a URL for a static resource
public
string
getStaticBaseUri()
Returns the prefix for all the generated static urls. By default /
public
string
path( string $path = null )
Generates a local path
public
UrlInterface
setBasePath( string $basePath )
Sets a base path for all the generated paths
public
UrlInterface
setBaseUri( string $baseUri )
Sets a prefix for all the URIs to be generated
public
UrlInterface
setStaticBaseUri( string $staticBaseUri )
Sets a prefix for all static URLs generated
Properties¶
protected
null | string
$basePath = null
protected
null | string
$baseUri = null
protected
RouterInterface | null
$router = null
protected
null | string
$staticBaseUri = null
Methods¶
__construct()¶
get()¶
public function get(
mixed $uri = null,
mixed $arguments = null,
bool $local = null,
mixed $baseUri = null,
bool $replaceArgs = false
): string;
Generates a URL
// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");
// Generate a URL for a predefined route
echo $url->get(
[
"for" => "blog-post",
"title" => "some-cool-stuff",
"year" => "2015",
]
);
// Generate a URL with GET arguments (/show/products?id=1&name=Carrots)
echo $url->get(
"show/products",
[
"id" => 1,
"name" => "Carrots",
]
);
// Generate an absolute URL by setting the third parameter as false.
echo $url->get(
"https://phalcon.io/",
null,
false
);
// Override existing query string keys instead of appending duplicates.
// Without the fifth argument: "http://example.com?page=1&page=5".
// With it set to true: "http://example.com?page=5".
echo $url->get(
"http://example.com?page=1",
["page" => 5],
null,
null,
true
);
getBasePath()¶
Returns the base path
getBaseUri()¶
Returns the prefix for all the generated urls. By default /
getStatic()¶
Generates a URL for a static resource
// Generate a URL for a static resource
echo $url->getStatic("img/logo.png");
// Generate a URL for a static predefined route
echo $url->getStatic(
[
"for" => "logo-cdn",
]
);
getStaticBaseUri()¶
Returns the prefix for all the generated static urls. By default /
path()¶
Generates a local path
setBasePath()¶
Sets a base path for all the generated paths
setBaseUri()¶
Sets a prefix for all the URIs to be generated
setStaticBaseUri()¶
Sets a prefix for all static URLs generated
Mvc\Url\Exception¶
Class Source on GitHub
Phalcon\Mvc\Url\Exception
Exceptions thrown in Phalcon\Mvc\Url will use this class
\Exception
Mvc\Url\Exceptions\MissingRouteName¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Url\ExceptionPhalcon\Mvc\Url\Exceptions\MissingRouteName
Uses Phalcon\Mvc\Url\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Url\Exceptions\RouteNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Url\ExceptionPhalcon\Mvc\Url\Exceptions\RouteNotFound
Uses Phalcon\Mvc\Url\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Url\Exceptions\RouterServiceUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\Url\ExceptionPhalcon\Mvc\Url\Exceptions\RouterServiceUnavailable
Uses Phalcon\Mvc\Url\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\Url\UrlInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\Url\UrlInterface
Phalcon\Mvc\Url\UrlInterface
Method Summary¶
public
string
get(mixed $uri = null,mixed $arguments = null,bool $local = null,mixed $baseUri = null,bool $replaceArgs = false)
Generates a URL
public
string|null
getBasePath()
Returns a base path
public
string
getBaseUri()
Returns the prefix for all the generated urls. By default /
public
string
path( string $path = null )
Generates a local path
public
UrlInterface
setBasePath( string $basePath )
Sets a base paths for all the generated paths
public
UrlInterface
setBaseUri( string $baseUri )
Sets a prefix to all the urls generated
Methods¶
get()¶
public function get(
mixed $uri = null,
mixed $arguments = null,
bool $local = null,
mixed $baseUri = null,
bool $replaceArgs = false
): string;
Generates a URL
getBasePath()¶
Returns a base path
getBaseUri()¶
Returns the prefix for all the generated urls. By default /
path()¶
Generates a local path
setBasePath()¶
Sets a base paths for all the generated paths
setBaseUri()¶
Sets a prefix to all the urls generated
Mvc\View¶
Class Source on GitHub
Phalcon\Mvc\View is a class for working with the "view" portion of the model-view-controller pattern. That is, it exists to help keep the view script separate from the model and controller scripts. It provides a system of helpers, output filters, and variable escaping.
use Phalcon\Mvc\View;
$view = new View();
// Setting views directory
$view->setViewsDir("app/views/");
$view->start();
// Shows recent posts view (app/views/posts/recent.phtml)
$view->render("posts", "recent");
$view->finish();
// Printing views output
echo $view->getContent();
stdClassPhalcon\Di\InjectablePhalcon\Mvc\View- implementsPhalcon\Mvc\ViewInterface,Phalcon\Events\EventsAwareInterface
Uses Closure · Phalcon\Di\DiInterface · Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Mvc\View\Engine\Php · Phalcon\Mvc\View\Exception · Phalcon\Mvc\View\Exceptions\InvalidEngineRegistration · Phalcon\Mvc\View\Exceptions\InvalidViewsDirType · Phalcon\Mvc\View\Exceptions\ViewNotFound · Phalcon\Mvc\View\Exceptions\ViewServicesUnavailable · Phalcon\Mvc\View\Exceptions\ViewsDirItemMustBeString · Phalcon\Mvc\View\Traits\ViewParamsTrait · Phalcon\Traits\Php\FileTrait · Phalcon\Traits\Support\Helper\Str\DirSeparatorTrait
Method Summary¶
public
__construct( array $options = [] )
Phalcon\Mvc\View constructor
public
mixed|null
__get( string $key )
Magic method to retrieve a variable passed to the view
public
bool
__isset( string $key )
Magic method to retrieve if a variable is set in the view
public
__set(string $key,mixed $value)
Magic method to pass variables to the views
public
static
cleanTemplateAfter()
Resets any template before layouts
public
static
cleanTemplateBefore()
Resets any "template before" layouts
public
static
disable()
Disables the auto-rendering process
public
static
disableLevel( mixed $level )
Disables a specific level of rendering
public
static
enable()
Enables the auto-rendering process
public
bool
exists( string $view )
Checks whether view exists
public
static
finish()
Finishes the render process by stopping the output buffering
public
string
getActionName()
Gets the name of the action rendered
public
string|array
getActiveRenderPath()
Returns the path (or paths) of the views that are currently rendered
public
string
getBasePath()
Gets base path
public
string
getControllerName()
Gets the name of the controller rendered
public
int
getCurrentRenderLevel()
public
ManagerInterface|null
getEventsManager()
Returns the internal event manager
public
string|null
getLayout()
Returns the name of the main view
public
string
getLayoutsDir()
Gets the current layouts sub-directory
public
string
getMainView()
Returns the name of the main view
public
string
getPartial(string $partialPath,mixed $params = null)
Renders a partial view
public
string
getPartialsDir()
Gets the current partials sub-directory
public
string
getRender(string $controllerName,string $actionName,array $params = [],mixed $configCallback = null)
Perform the automatic rendering returning the output as a string
public
int
getRenderLevel()
public
string|array
getViewsDir()
Gets views directory
public
bool
has( string $view )
Checks whether view exists
public
bool
isDisabled()
Whether automatic rendering is enabled
public
partial(string $partialPath,mixed $params = null)
Renders a partial view
public
static
pick( mixed $renderView )
Choose a different view to render instead of last-controller/last-action
public
bool
processRender(string $controllerName,string $actionName,array $params = [],bool $fireEvents = true)
Processes the view and templates; Fires events if needed
public
static
registerEngines( array $engines )
Register templating engines
public
static|false
render(string $controllerName,string $actionName,array $params = [])
Executes render process from dispatching data
public
static
reset()
Resets the view component to its factory default values
public
static
setBasePath( string $basePath )
Sets base path. Depending of your platform, always add a trailing slash
public
void
setEventsManager( ManagerInterface $eventsManager )
Sets the events manager
public
static
setLayout( string $layout )
Change the layout to be used instead of using the name of the latest
public
static
setLayoutsDir( string $layoutsDir )
Sets the layouts sub-directory. Must be a directory under the views
public
static
setMainView( string $viewPath )
Sets default view name. Must be a file without extension in the views
public
static
setParamToView(string $key,mixed $value)
Adds parameters to views (alias of setVar)
public
static
setPartialsDir( string $partialsDir )
Sets a partials sub-directory. Must be a directory under the views
public
static
setRenderLevel( int $level )
Sets the render level for the view
public
static
setTemplateAfter( mixed $templateAfter )
Sets a "template after" controller layout
public
static
setTemplateBefore( mixed $templateBefore )
Sets a template before the controller layout
public
static
setVars(array $params,bool $merge = true)
Set all the render params
public
static
setViewsDir( mixed $viewsDir )
Sets the views directory. Depending of your platform,
public
static
start()
Starts rendering process enabling the output buffering
public
string
toString(string $controllerName,string $actionName,array $params = [])
Renders the view and returns it as a string
protected
engineRender(array $engines,string $viewPath,bool $silence,bool $mustClean = true)
Checks whether view exists on registered extensions and render it
protected
array
getViewsDirs()
Gets views directories
protected
isAbsolutePath( string $path )
Checks if a path is absolute or not
protected
array
loadTemplateEngines()
Loads registered template engines, if none is registered it will use
Constants¶
int
LEVEL_ACTION_VIEW = 1
Render Level: To the action view
int
LEVEL_AFTER_TEMPLATE = 4
Render Level: Render to the templates "after"
int
LEVEL_BEFORE_TEMPLATE = 2
Render Level: To the templates "before"
int
LEVEL_LAYOUT = 3
Render Level: To the controller layout
int
LEVEL_MAIN_LAYOUT = 5
Render Level: To the main layout
int
LEVEL_NO_RENDER = 0
Render Level: No render any view
Properties¶
protected
string
$actionName
protected
array
$activeRenderPaths
protected
string
$basePath = ""
protected
string
$controllerName
protected
int
$currentRenderLevel = 0
protected
bool
$disabled = false
protected
array
$disabledLevels = []
protected
array|bool
$engines = false
protected
ManagerInterface|null
$eventsManager
protected
string|null
$layout = null
protected
string
$layoutsDir = ""
protected
string
$mainView = "index"
protected
array
$options = []
protected
array
$params = []
protected
string
$partialsDir = ""
protected
array|null
$pickView
protected
int
$renderLevel = 5
protected
array
$templatesAfter = []
protected
array
$templatesBefore = []
protected
array
$viewsDirs = []
Methods¶
__construct()¶
Phalcon\Mvc\View constructor
__get()¶
Magic method to retrieve a variable passed to the view
__isset()¶
Magic method to retrieve if a variable is set in the view
__set()¶
Magic method to pass variables to the views
cleanTemplateAfter()¶
Resets any template before layouts
cleanTemplateBefore()¶
Resets any "template before" layouts
disable()¶
Disables the auto-rendering process
disableLevel()¶
Disables a specific level of rendering
enable()¶
Enables the auto-rendering process
exists()¶
Checks whether view exists
finish()¶
Finishes the render process by stopping the output buffering
getActionName()¶
Gets the name of the action rendered
getActiveRenderPath()¶
Returns the path (or paths) of the views that are currently rendered
getBasePath()¶
Gets base path
getControllerName()¶
Gets the name of the controller rendered
getCurrentRenderLevel()¶
getEventsManager()¶
Returns the internal event manager
getLayout()¶
Returns the name of the main view
getLayoutsDir()¶
Gets the current layouts sub-directory
getMainView()¶
Returns the name of the main view
getPartial()¶
Renders a partial view
// Retrieve the contents of a partial with arguments
echo $this->getPartial(
"shared/footer",
[
"content" => $html,
]
);
getPartialsDir()¶
Gets the current partials sub-directory
getRender()¶
public function getRender(
string $controllerName,
string $actionName,
array $params = [],
mixed $configCallback = null
): string;
Perform the automatic rendering returning the output as a string
getRenderLevel()¶
getViewsDir()¶
Gets views directory
has()¶
Checks whether view exists
isDisabled()¶
Whether automatic rendering is enabled
partial()¶
Renders a partial view
// Show a partial inside another view with parameters
$this->partial(
"shared/footer",
[
"content" => $html,
]
);
pick()¶
Choose a different view to render instead of last-controller/last-action
use Phalcon\Mvc\Controller;
class ProductsController extends Controller
{
public function saveAction()
{
// Do some save stuff...
// Then show the list view
$this->view->pick("products/list");
}
}
processRender()¶
public function processRender(
string $controllerName,
string $actionName,
array $params = [],
bool $fireEvents = true
): bool;
Processes the view and templates; Fires events if needed
registerEngines()¶
Register templating engines
$this->view->registerEngines(
[
".phtml" => \Phalcon\Mvc\View\Engine\Php::class,
".volt" => \Phalcon\Mvc\View\Engine\Volt::class,
".mhtml" => \MyCustomEngine::class,
]
);
render()¶
public function render(
string $controllerName,
string $actionName,
array $params = []
): static|false;
Executes render process from dispatching data
// Shows recent posts view (app/views/posts/recent.phtml)
$view->start()->render("posts", "recent")->finish();
reset()¶
Resets the view component to its factory default values
setBasePath()¶
Sets base path. Depending of your platform, always add a trailing slash or backslash
setEventsManager()¶
Sets the events manager
setLayout()¶
Change the layout to be used instead of using the name of the latest controller name
setLayoutsDir()¶
Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash
setMainView()¶
Sets default view name. Must be a file without extension in the views directory
setParamToView()¶
Adds parameters to views (alias of setVar)
setPartialsDir()¶
Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash
setRenderLevel()¶
Sets the render level for the view
// Render the view related to the controller only
$this->view->setRenderLevel(
View::LEVEL_LAYOUT
);
setTemplateAfter()¶
Sets a "template after" controller layout
setTemplateBefore()¶
Sets a template before the controller layout
setVars()¶
Set all the render params
setViewsDir()¶
Sets the views directory. Depending of your platform, always add a trailing slash or backslash
start()¶
Starts rendering process enabling the output buffering
toString()¶
Renders the view and returns it as a string
engineRender()¶
protected function engineRender(
array $engines,
string $viewPath,
bool $silence,
bool $mustClean = true
);
Checks whether view exists on registered extensions and render it
getViewsDirs()¶
Gets views directories
isAbsolutePath()¶
Checks if a path is absolute or not
loadTemplateEngines()¶
Loads registered template engines, if none is registered it will use Phalcon\Mvc\View\Engine\Php
Mvc\ViewBaseInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\View and Phalcon\Mvc\View\Simple
Phalcon\Mvc\ViewBaseInterface
Uses Phalcon\Cache\Adapter\AdapterInterface
Method Summary¶
public
string
getContent()
Returns cached output from another view stage
public
array
getParamsToView()
Returns parameters to views
public
string|array
getViewsDir()
Gets views directory
public
partial(string $partialPath,mixed $params = null)
Renders a partial view
public
setContent( string $content )
Externally sets the view content
public
setParamToView(string $key,mixed $value)
Adds parameters to views (alias of setVar)
public
setVar(string $key,mixed $value)
Adds parameters to views
public
setViewsDir( string $viewsDir )
Sets views directory. Depending of your platform, always add a trailing
Methods¶
getContent()¶
Returns cached output from another view stage
getParamsToView()¶
Returns parameters to views
getViewsDir()¶
Gets views directory
partial()¶
Renders a partial view
setContent()¶
Externally sets the view content
setParamToView()¶
Adds parameters to views (alias of setVar)
setVar()¶
Adds parameters to views
setViewsDir()¶
Sets views directory. Depending of your platform, always add a trailing slash or backslash
Mvc\ViewInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\View
Phalcon\Mvc\ViewBaseInterfacePhalcon\Mvc\ViewInterface
Method Summary¶
public
cleanTemplateAfter()
Resets any template before layouts
public
cleanTemplateBefore()
Resets any template before layouts
public
disable()
Disables the auto-rendering process
public
enable()
Enables the auto-rendering process
public
finish()
Finishes the render process by stopping the output buffering
public
string
getActionName()
Gets the name of the action rendered
public
string|array
getActiveRenderPath()
Returns the path of the view that is currently rendered
public
string
getBasePath()
Gets base path
public
string
getControllerName()
Gets the name of the controller rendered
public
string|null
getLayout()
Returns the name of the main view
public
string
getLayoutsDir()
Gets the current layouts sub-directory
public
string
getMainView()
Returns the name of the main view
public
string
getPartialsDir()
Gets the current partials sub-directory
public
bool
isDisabled()
Whether the automatic rendering is disabled
public
pick( string $renderView )
Choose a view different to render than last-controller/last-action
public
registerEngines( array $engines )
Register templating engines
public
ViewInterface|bool
render(string $controllerName,string $actionName,array $params = [])
Executes render process from dispatching data
public
reset()
Resets the view component to its factory default values
public
setBasePath( string $basePath )
Sets base path. Depending of your platform, always add a trailing slash
public
setLayout( string $layout )
Change the layout to be used instead of using the name of the latest
public
setLayoutsDir( string $layoutsDir )
Sets the layouts sub-directory. Must be a directory under the views
public
setMainView( string $viewPath )
Sets default view name. Must be a file without extension in the views
public
setPartialsDir( string $partialsDir )
Sets a partials sub-directory. Must be a directory under the views
public
ViewInterface
setRenderLevel( int $level )
Sets the render level for the view
public
setTemplateAfter( mixed $templateAfter )
Appends template after controller layout
public
setTemplateBefore( mixed $templateBefore )
Appends template before controller layout
public
start()
Starts rendering process enabling the output buffering
Methods¶
cleanTemplateAfter()¶
Resets any template before layouts
cleanTemplateBefore()¶
Resets any template before layouts
disable()¶
Disables the auto-rendering process
enable()¶
Enables the auto-rendering process
finish()¶
Finishes the render process by stopping the output buffering
getActionName()¶
Gets the name of the action rendered
getActiveRenderPath()¶
Returns the path of the view that is currently rendered
getBasePath()¶
Gets base path
getControllerName()¶
Gets the name of the controller rendered
getLayout()¶
Returns the name of the main view
getLayoutsDir()¶
Gets the current layouts sub-directory
getMainView()¶
Returns the name of the main view
getPartialsDir()¶
Gets the current partials sub-directory
isDisabled()¶
Whether the automatic rendering is disabled
pick()¶
Choose a view different to render than last-controller/last-action
registerEngines()¶
Register templating engines
render()¶
public function render(
string $controllerName,
string $actionName,
array $params = []
): ViewInterface|bool;
Executes render process from dispatching data
reset()¶
Resets the view component to its factory default values
setBasePath()¶
Sets base path. Depending of your platform, always add a trailing slash or backslash
setLayout()¶
Change the layout to be used instead of using the name of the latest controller name
setLayoutsDir()¶
Sets the layouts sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash
setMainView()¶
Sets default view name. Must be a file without extension in the views directory
setPartialsDir()¶
Sets a partials sub-directory. Must be a directory under the views directory. Depending of your platform, always add a trailing slash or backslash
setRenderLevel()¶
Sets the render level for the view
setTemplateAfter()¶
Appends template after controller layout
setTemplateBefore()¶
Appends template before controller layout
start()¶
Starts rendering process enabling the output buffering
Mvc\View\Engine\AbstractEngine¶
Abstract Source on GitHub
All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\Mvc\View component.
stdClassPhalcon\Di\InjectablePhalcon\Mvc\View\Engine\AbstractEngine- implementsPhalcon\Mvc\View\Engine\EngineInterface,Phalcon\Events\EventsAwareInterface
Uses Phalcon\Di\DiInterface · Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Mvc\ViewBaseInterface
Method Summary¶
public
__construct(ViewBaseInterface $view,DiInterface $container = null)
Phalcon\Mvc\View\Engine constructor
public
string
getContent()
Returns cached output on another view stage
public
ManagerInterface|null
getEventsManager()
Returns the internal event manager
public
ViewBaseInterface
getView()
Returns the view component related to the adapter
public
void
partial(string $partialPath,mixed $params = null)
Renders a partial inside another view
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
Properties¶
protected
ManagerInterface|null
$eventsManager = null
protected
ViewBaseInterface
$view
Methods¶
__construct()¶
Phalcon\Mvc\View\Engine constructor
getContent()¶
Returns cached output on another view stage
getEventsManager()¶
Returns the internal event manager
getView()¶
Returns the view component related to the adapter
partial()¶
Renders a partial inside another view
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\View\Engine\EngineInterface¶
Interface Source on GitHub
Interface for Phalcon\Mvc\View engine adapters
Phalcon\Mvc\View\Engine\EngineInterface
Method Summary¶
public
string
getContent()
Returns cached output on another view stage
public
void
partial(string $partialPath,mixed $params = null)
Renders a partial inside another view
public
render(string $path,mixed $params,bool $mustClean = false)
Renders a view using the template engine
Methods¶
getContent()¶
Returns cached output on another view stage
partial()¶
Renders a partial inside another view
render()¶
Renders a view using the template engine
TODO: Change params to array type
Mvc\View\Engine\Php¶
Class Source on GitHub
Adapter to use PHP itself as templating engine
stdClassPhalcon\Di\InjectablePhalcon\Mvc\View\Engine\AbstractEnginePhalcon\Mvc\View\Engine\Php
Method Summary¶
Methods¶
render()¶
Renders a view using the template engine
Mvc\View\Engine\Volt¶
Class Source on GitHub
Designer friendly and fast template engine for PHP written in Zephir/C
stdClassPhalcon\Di\InjectablePhalcon\Mvc\View\Engine\AbstractEnginePhalcon\Mvc\View\Engine\Volt- implementsPhalcon\Events\EventsAwareInterface
Uses Phalcon\Di\DiInterface · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Html\Link\Link · Phalcon\Html\Link\Serializer\Header · Phalcon\Mvc\View\Engine\Volt\Compiler · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidHaystack · Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroNotFound · Phalcon\Mvc\View\Engine\Volt\Exceptions\MbstringRequired · Phalcon\Mvc\View\Exception · Phalcon\Traits\Php\InfoTrait
Method Summary¶
public
mixed
callMacro(string $name,array $arguments = [])
Checks if a macro is defined and calls it
public
string
convertEncoding(string $text,string $from,string $to)
Performs a string conversion
public
Compiler
getCompiler()
Returns the Volt's compiler
public
ManagerInterface|null
getEventsManager()
Returns the internal event manager
public
array
getOptions()
Return Volt's options
public
bool
isIncluded(mixed $needle,mixed $haystack)
Checks if the needle is included in the haystack
public
int
length( mixed $item )
Length filter. If an array/object is passed a count is performed otherwise a strlen/mb_strlen
public
string
preload( mixed $parameters )
Parses the preload element passed and sets the necessary link headers
public
render(string $path,mixed $params,bool $mustClean = false)
Renders a view using the template engine
public
void
setEventsManager( ManagerInterface $eventsManager )
Sets the events manager
public
setOptions( array $options )
Set Volt's options
public
slice(mixed $value,int $start = 0,mixed $end = null)
Extracts a slice from a string/array/traversable object value
public
array
sort( array $value )
Sorts an array
Properties¶
protected
Compiler
$compiler
protected
ManagerInterface|null
$eventsManager
protected
array
$macros = []
protected
array
$options = []
Methods¶
callMacro()¶
Checks if a macro is defined and calls it
@params string name @params array arguments
convertEncoding()¶
Performs a string conversion
getCompiler()¶
Returns the Volt's compiler
getEventsManager()¶
Returns the internal event manager
getOptions()¶
Return Volt's options
isIncluded()¶
Checks if the needle is included in the haystack
length()¶
Length filter. If an array/object is passed a count is performed otherwise a strlen/mb_strlen
preload()¶
Parses the preload element passed and sets the necessary link headers @todo find a better way to handle this
render()¶
Renders a view using the template engine
setEventsManager()¶
Sets the events manager
setOptions()¶
Set Volt's options
slice()¶
Extracts a slice from a string/array/traversable object value
sort()¶
Sorts an array
Mvc\View\Engine\Volt\Compiler¶
Class Source on GitHub
This class reads and compiles Volt templates into PHP plain code
$compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler();
$compiler->compile("views/partials/header.volt");
require $compiler->getCompiledTemplatePath();
Phalcon\Mvc\View\Engine\Volt\Compiler- implementsPhalcon\Di\InjectionAwareInterface
Uses Closure · Phalcon\Di\DiInterface · Phalcon\Di\InjectionAwareInterface · Phalcon\Mvc\ViewBaseInterface · Phalcon\Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile · Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatement · Phalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidExtension · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidOptionType · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathType · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidStatement · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition · Phalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition · Phalcon\Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined · Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound · Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable · Phalcon\Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision · Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression · Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter · Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType · Phalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement · Phalcon\Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable · Phalcon\Traits\Php\FileTrait
Method Summary¶
public
__construct( ViewBaseInterface $view = null )
Phalcon\Mvc\View\Engine\Volt\Compiler
public
static
addExtension( mixed $extension )
Registers a Volt's extension
public
static
addFilter(string $name,mixed $definition)
Register a new filter in the compiler
public
static
addFunction(string $name,mixed $definition)
Register a new function in the compiler
public
string
attributeReader( array $expr )
Resolves attribute reading
public
compile(string $templatePath,bool $extendsMode = false)
Compiles a template into a file applying the compiler options
public
string
compileAutoEscape(array $statement,bool $extendsMode)
Compiles a "autoescape" statement returning PHP code
public
string
compileCall(array $statement,bool $extendsMode)
Compiles calls to macros
public
string
compileCase(array $statement,bool $caseClause = true)
Compiles a "case"/"default" clause returning PHP code
public
string
compileDo( array $statement )
Compiles a "do" statement returning PHP code
public
string
compileEcho( array $statement )
Compiles a {{ }} statement returning PHP code
public
string
compileElseIf( array $statement )
Compiles a "elseif" statement returning PHP code
public
compileFile(string $path,string $compiledPath,bool $extendsMode = false)
Compiles a template into a file forcing the destination path
public
string
compileForElse()
Generates a 'forelse' PHP code
public
string
compileForeach(array $statement,bool $extendsMode = false)
Compiles a "foreach" intermediate code representation into plain PHP code
public
string
compileIf(array $statement,bool $extendsMode = false)
Compiles a 'if' statement returning PHP code
public
string
compileInclude( array $statement )
Compiles a 'include' statement returning PHP code
public
string
compileMacro(array $statement,bool $extendsMode)
Compiles macros
public
string
compileReturn( array $statement )
Compiles a "return" statement returning PHP code
public
string
compileSet( array $statement )
Compiles a "set" statement returning PHP code. The method accepts an
public
string
compileString(string $viewCode,bool $extendsMode = false)
Compiles a template into a string
public
string
compileSwitch(array $statement,bool $extendsMode = false)
Compiles a 'switch' statement returning PHP code
public
string
expression(array $expr,bool $doubleQuotes = false)
Resolves an expression node in an AST volt tree
public
fireExtensionEvent(string $name,array $arguments = [])
Fires an event to registered extensions
public
string
functionCall(array $expr,bool $doubleQuotes = false)
Resolves function intermediate code into PHP function calls
public
string
getCompiledTemplatePath()
Returns the path to the last compiled template
public
DiInterface
getDI()
Returns the internal dependency injector
public
array
getExtensions()
Returns the list of extensions registered in Volt
public
array
getFilters()
Register the user registered filters
public
array
getFunctions()
Register the user registered functions
public
string|null
getOption( string $option )
Returns a compiler's option
public
array
getOptions()
Returns the compiler options
public
string
getTemplatePath()
Returns the path that is currently being compiled
public
string
getUniquePrefix()
Return a unique prefix to be used as prefix for compiled variables and
public
array
parse( string $viewCode )
Parses a Volt template returning its intermediate representation
public
string
resolveTest(array $test,string $left)
Resolves filter intermediate code into a valid PHP expression
public
void
setDI( DiInterface $container )
Sets the dependency injector
public
static
setOption(string $option,mixed $value)
Sets a single compiler option
public
static
setOptions( array $options )
Sets the compiler options
public
static
setUniquePrefix( string $prefix )
Set a unique prefix to be used as prefix for compiled variables
protected
array|string
compileSource(string $viewCode,bool $extendsMode = false)
Compiles a Volt source code returning a PHP plain version
protected
getFinalPath( string $path )
Gets the final path with VIEW
protected
string
resolveFilter(array $filter,string $left)
Resolves filter intermediate code into PHP function calls
protected
string
statementList(array $statements,bool $extendsMode = false)
Traverses a statement list compiling each of its nodes
protected
statementListOrExtends( mixed $statements )
Compiles a block of statements
Properties¶
protected
bool
$autoescape = false
protected
int
$blockLevel = 0
protected
array|null
$blocks
TODO: Make array only?
protected
string|null
$compiledTemplatePath
protected
DiInterface|null
$container = null
protected
string|null
$currentBlock = null
protected
string|null
$currentPath = null
protected
int
$exprLevel = 0
protected
bool
$extended = false
protected
array|bool
$extendedBlocks
TODO: Make it always array
protected
array
$extensions = []
protected
array
$filters = []
protected
array
$forElsePointers = []
protected
int
$foreachLevel = 0
protected
array
$functions = []
protected
int
$level = 0
protected
array
$loopPointers = []
protected
array
$macros = []
protected
array
$options = []
protected
string
$prefix = ""
protected
ViewBaseInterface|null
$view
Methods¶
__construct()¶
Phalcon\Mvc\View\Engine\Volt\Compiler
addExtension()¶
Registers a Volt's extension
addFilter()¶
Register a new filter in the compiler
addFunction()¶
Register a new function in the compiler
attributeReader()¶
Resolves attribute reading
compile()¶
Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled
compileAutoEscape()¶
Compiles a "autoescape" statement returning PHP code
compileCall()¶
Compiles calls to macros
compileCase()¶
Compiles a "case"/"default" clause returning PHP code
compileDo()¶
Compiles a "do" statement returning PHP code
compileEcho()¶
Compiles a {{ }} statement returning PHP code
compileElseIf()¶
Compiles a "elseif" statement returning PHP code
compileFile()¶
Compiles a template into a file forcing the destination path
compileForElse()¶
Generates a 'forelse' PHP code
compileForeach()¶
Compiles a "foreach" intermediate code representation into plain PHP code
compileIf()¶
Compiles a 'if' statement returning PHP code
compileInclude()¶
Compiles a 'include' statement returning PHP code
compileMacro()¶
Compiles macros
compileReturn()¶
Compiles a "return" statement returning PHP code
compileSet()¶
Compiles a "set" statement returning PHP code. The method accepts an
array produced by the Volt parser and creates the set statement in PHP.
This method is not particularly useful in development, since it requires
advanced knowledge of the Volt parser.
<?php
use Phalcon\Mvc\View\Engine\Volt\Compiler;
$compiler = new Compiler();
// {% set a = ['first': 1] %}
$source = [
"type" => 306,
"assignments" => [
[
"variable" => [
"type" => 265,
"value" => "a",
"file" => "eval code",
"line" => 1
],
"op" => 61,
"expr" => [
"type" => 360,
"left" => [
[
"expr" => [
"type" => 258,
"value" => "1",
"file" => "eval code",
"line" => 1
],
"name" => "first",
"file" => "eval code",
"line" => 1
]
],
"file" => "eval code",
"line" => 1
],
"file" => "eval code",
"line" => 1
]
]
];
echo $compiler->compileSet($source);
// <?php $a = ['first' => 1]; ?>";
compileString()¶
Compiles a template into a string
compileSwitch()¶
Compiles a 'switch' statement returning PHP code
expression()¶
Resolves an expression node in an AST volt tree
fireExtensionEvent()¶
Fires an event to registered extensions
functionCall()¶
Resolves function intermediate code into PHP function calls
getCompiledTemplatePath()¶
Returns the path to the last compiled template
getDI()¶
Returns the internal dependency injector
getExtensions()¶
Returns the list of extensions registered in Volt
getFilters()¶
Register the user registered filters
getFunctions()¶
Register the user registered functions
getOption()¶
Returns a compiler's option
getOptions()¶
Returns the compiler options
getTemplatePath()¶
Returns the path that is currently being compiled
getUniquePrefix()¶
Return a unique prefix to be used as prefix for compiled variables and contexts
parse()¶
Parses a Volt template returning its intermediate representation
resolveTest()¶
Resolves filter intermediate code into a valid PHP expression
setDI()¶
Sets the dependency injector
setOption()¶
Sets a single compiler option
setOptions()¶
Sets the compiler options
setUniquePrefix()¶
Set a unique prefix to be used as prefix for compiled variables
compileSource()¶
Compiles a Volt source code returning a PHP plain version
getFinalPath()¶
Gets the final path with VIEW
resolveFilter()¶
Resolves filter intermediate code into PHP function calls
statementList()¶
Traverses a statement list compiling each of its nodes
statementListOrExtends()¶
Compiles a block of statements
Mvc\View\Engine\Volt\Exception¶
Class Source on GitHub
Class for exceptions thrown by Phalcon\Mvc\View
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFilePhalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatementPhalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithDataPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefixPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidExtensionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidHaystackPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentationPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidOptionTypePhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturnPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathTypePhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidStatementPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinitionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinitionPhalcon\Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefinedPhalcon\Mvc\View\Engine\Volt\Exceptions\MacroNotFoundPhalcon\Mvc\View\Engine\Volt\Exceptions\MbstringRequiredPhalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFoundPhalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenablePhalcon\Mvc\View\Engine\Volt\Exceptions\TemplatePathCollisionPhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpressionPhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterPhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterTypePhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatementPhalcon\Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable
Uses Phalcon\Mvc\View\Exception
Method Summary¶
public
__construct(string $message = "",array $statement = [],int $code = 0,\Exception $previous = null)
public
array
getStatement()
Gets currently parsed statement (if any).
Properties¶
protected
array
$statement = []
Methods¶
__construct()¶
public function __construct(
string $message = "",
array $statement = [],
int $code = 0,
\Exception $previous = null
);
getStatement()¶
Gets currently parsed statement (if any).
Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\CannotOpenCompiledFile
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\CorruptedStatement¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatement
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\CorruptedStatementWithData
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidCompilationPrefix
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidExtension¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidExtension
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidHaystack¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidHaystack
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidIntermediateRepresentation
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidOptionType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidOptionType
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathClosureReturn
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidPathType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidPathType
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidStatement¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidStatement
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFilterDefinition
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\InvalidUserFunctionDefinition
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\MacroAlreadyDefined
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\MacroNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\MacroNotFound
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\MbstringRequired¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\MbstringRequired
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotFound
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\TemplateFileNotOpenable
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\TemplatePathCollision
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltExpression
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilter
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltFilterType
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\UnknownVoltStatement
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Engine\Volt\Exceptions\VoltDirectoryNotWritable
Uses Phalcon\Mvc\View\Engine\Volt\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Exception¶
Class Source on GitHub
Phalcon\Mvc\View\Exception
Class for exceptions thrown by Phalcon\Mvc\View
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Engine\Volt\ExceptionPhalcon\Mvc\View\Exceptions\InvalidEngineRegistrationPhalcon\Mvc\View\Exceptions\InvalidViewsDirTypePhalcon\Mvc\View\Exceptions\SimpleViewNotFoundPhalcon\Mvc\View\Exceptions\SimpleViewServicesUnavailablePhalcon\Mvc\View\Exceptions\ViewNotFoundPhalcon\Mvc\View\Exceptions\ViewServicesUnavailablePhalcon\Mvc\View\Exceptions\ViewsDirItemMustBeString
Mvc\View\Exceptions\InvalidEngineRegistration¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Exceptions\InvalidEngineRegistration
Uses Phalcon\Mvc\View\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Exceptions\InvalidViewsDirType¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Exceptions\InvalidViewsDirType
Uses Phalcon\Mvc\View\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Exceptions\SimpleViewNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Exceptions\SimpleViewNotFound
Uses Phalcon\Mvc\View\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Exceptions\SimpleViewServicesUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Exceptions\SimpleViewServicesUnavailable
Uses Phalcon\Mvc\View\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Exceptions\ViewNotFound¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Exceptions\ViewNotFound
Uses Phalcon\Mvc\View\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Exceptions\ViewServicesUnavailable¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Exceptions\ViewServicesUnavailable
Uses Phalcon\Mvc\View\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Exceptions\ViewsDirItemMustBeString¶
Class Source on GitHub
\ExceptionPhalcon\Mvc\View\ExceptionPhalcon\Mvc\View\Exceptions\ViewsDirItemMustBeString
Uses Phalcon\Mvc\View\Exception
Method Summary¶
Methods¶
__construct()¶
Mvc\View\Simple¶
Class Source on GitHub
This component allows to render views without hierarchical levels
use Phalcon\Mvc\View\Simple as View;
$view = new View();
// Render a view
echo $view->render(
"templates/my-view",
[
"some" => $param,
]
);
// Or with filename with extension
echo $view->render(
"templates/my-view.volt",
[
"parameter" => $here,
]
);
stdClassPhalcon\Di\InjectablePhalcon\Mvc\View\Simple- implementsPhalcon\Mvc\ViewBaseInterface,Phalcon\Events\EventsAwareInterface
Uses Closure · Phalcon\Di\DiInterface · Phalcon\Di\Injectable · Phalcon\Events\EventsAwareInterface · Phalcon\Events\ManagerInterface · Phalcon\Mvc\ViewBaseInterface · Phalcon\Mvc\View\Engine\EngineInterface · Phalcon\Mvc\View\Engine\Php · Phalcon\Mvc\View\Exceptions\InvalidEngineRegistration · Phalcon\Mvc\View\Exceptions\SimpleViewNotFound · Phalcon\Mvc\View\Exceptions\SimpleViewServicesUnavailable · Phalcon\Mvc\View\Traits\ViewParamsTrait · Phalcon\Traits\Php\FileTrait · Phalcon\Traits\Support\Helper\Str\DirSeparatorTrait
Method Summary¶
public
__construct( array $options = [] )
Phalcon\Mvc\View\Simple constructor
public
mixed|null
__get( string $key )
Magic method to retrieve a variable passed to the view
public
void
__set(string $key,mixed $value)
Magic method to pass variables to the views
public
string
getActiveRenderPath()
Returns the path of the view that is currently rendered
public
ManagerInterface|null
getEventsManager()
Returns the internal event manager
public
string
getViewsDir()
Gets views directory
public
void
partial(string $partialPath,mixed $params = null)
Renders a partial view
public
void
registerEngines( array $engines )
Register templating engines
public
string
render(string $path,array $params = [])
Renders a view
public
void
setEventsManager( ManagerInterface $eventsManager )
Sets the events manager
public
static
setParamToView(string $key,mixed $value)
Adds parameters to views (alias of setVar)
public
static
setVars(array $params,bool $merge = true)
Set all the render params
public
void
setViewsDir( string $viewsDir )
Sets views directory
protected
void
internalRender(string $path,mixed $params)
Tries to render the view with every engine registered in the component
protected
array
loadTemplateEngines()
Loads registered template engines, if none are registered it will use
Properties¶
protected
string
$activeRenderPath
protected
EngineInterface[]|false
$engines = false
protected
ManagerInterface|null
$eventsManager
protected
array
$options = []
protected
string
$viewsDir
Methods¶
__construct()¶
Phalcon\Mvc\View\Simple constructor
__get()¶
Magic method to retrieve a variable passed to the view
__set()¶
Magic method to pass variables to the views
getActiveRenderPath()¶
Returns the path of the view that is currently rendered
getEventsManager()¶
Returns the internal event manager
getViewsDir()¶
Gets views directory
partial()¶
Renders a partial view
// Show a partial inside another view with parameters
$this->partial(
"shared/footer",
[
"content" => $html,
]
);
registerEngines()¶
Register templating engines
$this->view->registerEngines(
[
".phtml" => \Phalcon\Mvc\View\Engine\Php::class,
".volt" => \Phalcon\Mvc\View\Engine\Volt::class,
".mhtml" => \MyCustomEngine::class,
]
);
render()¶
Renders a view
setEventsManager()¶
Sets the events manager
setParamToView()¶
Adds parameters to views (alias of setVar)
setVars()¶
Set all the render params
setViewsDir()¶
Sets views directory
internalRender()¶
Tries to render the view with every engine registered in the component
loadTemplateEngines()¶
Loads registered template engines, if none are registered it will use Phalcon\Mvc\View\Engine\Php