Phalcon mvc
NOTE
All classes are prefixed with Phalcon
Mvc\Application¶
-
Namespace
Phalcon\Mvc
-
Uses
Closure
Phalcon\Application\AbstractApplication
Phalcon\Di\DiInterface
Phalcon\Events\ManagerInterface
Phalcon\Http\ResponseInterface
Phalcon\Mvc\Application\Exception
Phalcon\Mvc\ModuleDefinitionInterface
Phalcon\Mvc\Router\RouteInterface
-
Extends
AbstractApplication
-
Implements
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();
Properties¶
//
protected $implicitView = true;
//
protected $sendCookies = true;
//
protected $sendHeaders = true;
Methods¶
Handles a MVC request Enables or disables sending cookies by each request handling Enables or disables sending headers by each request handling By default. The view is implicitly buffering all the output You can full disable the view component using this methodMvc\Application\Exception¶
-
Namespace
Phalcon\Mvc\Application
-
Uses
-
Extends
\Phalcon\Application\Exception
-
Implements
Phalcon\Mvc\Application\Exception
Exceptions thrown in Phalcon\Mvc\Application class will use this class
Mvc\Controller ¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Di\Injectable
-
Extends
Injectable
-
Implements
ControllerInterface
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",
]
);
}
}
Methods¶
Phalcon\Mvc\Controller constructorMvc\Controller\BindModelInterface ¶
-
Namespace
Phalcon\Mvc\Controller
-
Uses
-
Extends
-
Implements
Interface for Phalcon\Mvc\Controller
Methods¶
Return the model name associated with this controllerMvc\ControllerInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
-
Extends
-
Implements
Interface for controller handlers
Mvc\Dispatcher¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Dispatcher\AbstractDispatcher
Phalcon\Events\ManagerInterface
Phalcon\Http\ResponseInterface
Phalcon\Mvc\Dispatcher\Exception
-
Extends
BaseDispatcher
-
Implements
DispatcherInterface
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();
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$dispatcher->setDI($di);
$dispatcher->setControllerName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);
$controller = $dispatcher->dispatch();
Properties¶
//
protected $defaultAction = index;
//
protected $defaultHandler = index;
//
protected $handlerSuffix = Controller;
Methods¶
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",
]
);
Mvc\Dispatcher\Exception¶
-
Namespace
Phalcon\Mvc\Dispatcher
-
Uses
-
Extends
\Phalcon\Dispatcher\Exception
-
Implements
Phalcon\Mvc\Dispatcher\Exception
Exceptions thrown in Phalcon\Mvc\Dispatcher will use this class
Mvc\DispatcherInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Dispatcher\DispatcherInterface
-
Extends
DispatcherInterfaceBase
-
Implements
Interface for Phalcon\Mvc\Dispatcher
Methods¶
Returns the active controller in the dispatcher Gets last dispatched controller name Returns the latest dispatched controller Sets the controller name to be dispatched Sets the default controller suffix Sets the default controller nameMvc\EntityInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\EntityInterface
Interface for Phalcon\Mvc\Collection and Phalcon\Mvc\Model
Methods¶
Reads an attribute value by its name Writes an attribute value by its nameMvc\Micro¶
-
Namespace
Phalcon\Mvc
-
Uses
ArrayAccess
Closure
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\LazyLoader
Phalcon\Mvc\Micro\MiddlewareInterface
Phalcon\Mvc\Model\BinderInterface
Phalcon\Mvc\Router\RouteInterface
Throwable
-
Extends
Injectable
-
Implements
ArrayAccess
EventsAwareInterface
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");
Properties¶
//
protected $activeHandler;
//
protected $afterBindingHandlers;
//
protected $afterHandlers;
//
protected $beforeHandlers;
//
protected $container;
//
protected $errorHandler;
//
protected $eventsManager;
//
protected $finishHandlers;
//
protected $handlers;
//
protected $modelBinder;
//
protected $notFoundHandler;
//
protected $responseHandler;
//
protected $returnedValue;
//
protected $router;
//
protected $stopped;
Methods¶
Phalcon\Mvc\Micro constructor Appends an 'after' middleware to be called after execute the route Appends a afterBinding middleware to be called after model binding Appends a before middleware to be called before execute the route Maps a route to a handler that only matches if the HTTP method is DELETE Sets a handler that will be called when an exception is thrown handling the route Appends a 'finish' middleware to be called when the request is finished Maps a route to a handler that only matches if the HTTP method is GET Return the handler that will be called for the matched route Returns bound models from binder instance Returns the internal event manager Returns the internal handlers attached to the application Gets model binder Returns the value returned by the executed handler Returns the internal router used by the application Obtains a service from the DI Obtains a shared service from the DI Handle the whole request Checks if a service is registered in the DI Maps a route to a handler that only matches if the HTTP method is HEAD Maps a route to a handler without any HTTP method constraint Mounts a collection of handlers Sets a handler that will be called when the router doesn't match any of the defined routes Check if a service is registered in the internal services container using the array syntax Allows to obtain a shared service in the internal services container using the array syntax Allows to register a shared service in the internal services container using the array syntax Removes a service from the internal services container using the array syntax Maps a route to a handler that only matches if the HTTP method is OPTIONS Maps a route to a handler that only matches if the HTTP method is PATCH Maps a route to a handler that only matches if the HTTP method is POST Maps a route to a handler that only matches if the HTTP method is PUT Sets externally the handler that must be called by the matched route Sets the DependencyInjector container Sets the events manager Sets model binder Appends a custom 'response' handler to be called instead of the default response handlerpublic function setService( string $serviceName, mixed $definition, bool $shared = bool ): ServiceInterface;
Mvc\Micro\Collection¶
-
Namespace
Phalcon\Mvc\Micro
-
Uses
-
Extends
-
Implements
CollectionInterface
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);
Properties¶
Methods¶
public function delete( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
public function get( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
public function head( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
public function map( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
public function mapVia( string $routePattern, mixed $handler, mixed $method, string $name = null ): CollectionInterface;
public function options( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
public function patch( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
public function post( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
public function put( string $routePattern, mixed $handler, string $name = null ): CollectionInterface;
Mvc\Micro\CollectionInterface ¶
-
Namespace
Phalcon\Mvc\Micro
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\Micro\CollectionInterface
Interface for Phalcon\Mvc\Micro\Collection
Methods¶
public function delete( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
public function get( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
public function head( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
public function map( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
public function options( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
public function patch( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
public function post( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
public function put( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
Mvc\Micro\Exception¶
-
Namespace
Phalcon\Mvc\Micro
-
Uses
-
Extends
Phalcon\Exception
-
Implements
Exceptions thrown in Phalcon\Mvc\Micro will use this class
Mvc\Micro\LazyLoader¶
-
Namespace
Phalcon\Mvc\Micro
-
Uses
Phalcon\Mvc\Model\BinderInterface
-
Extends
-
Implements
Phalcon\Mvc\Micro\LazyLoader
Lazy-Load of handlers for Mvc\Micro using auto-loading
Properties¶
Methods¶
Phalcon\Mvc\Micro\LazyLoader constructorpublic function callMethod( string $method, mixed $arguments, BinderInterface $modelBinder = null );
Mvc\Micro\MiddlewareInterface ¶
-
Namespace
Phalcon\Mvc\Micro
-
Uses
Phalcon\Mvc\Micro
-
Extends
-
Implements
Allows to implement Phalcon\Mvc\Micro middleware in classes
Methods¶
Calls the middlewareMvc\Model ¶
-
Namespace
Phalcon\Mvc
-
Uses
JsonSerializable
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Db\Column
Phalcon\Db\DialectInterface
Phalcon\Db\Enum
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\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\Collection
Phalcon\Collection\CollectionInterface
Serializable
-
Extends
AbstractInjectionAware
-
Implements
EntityInterface
JsonSerializable
ModelInterface
ResultInterface
Serializable
Phalcon\Mvc\Model
Phalcon\Mvc\Model connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. It‘s an implementation of the object-relational mapping (ORM).
A model represents the information (data) of the application and the rules to manipulate that data. Models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, each table in your database will correspond to one model in your application. The bulk of your application's business logic will be concentrated in the models.
Phalcon\Mvc\Model is the first ORM written in Zephir/C languages for PHP, giving to developers high performance when interacting with databases while is also easy to use.
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() === false) {
echo "Umh, We can store robots: ";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message;
}
} else {
echo "Great, a new robot was saved successfully!";
}
Constants¶
const DIRTY_STATE_DETACHED = 2;
const DIRTY_STATE_PERSISTENT = 0;
const DIRTY_STATE_TRANSIENT = 1;
const OP_CREATE = 1;
const OP_DELETE = 3;
const OP_NONE = 0;
const OP_UPDATE = 2;
const TRANSACTION_INDEX = transaction;
Properties¶
//
protected $dirtyState = 1;
/**
* @var array
*/
protected $dirtyRelated;
/**
* @var array
*/
protected $errorMessages;
//
protected $modelsManager;
//
protected $modelsMetaData;
/**
* @var array
*/
protected $related;
//
protected $operationMade = 0;
/**
* @var array
*/
protected $oldSnapshot;
//
protected $skipped;
//
protected $snapshot;
//
protected $transaction;
//
protected $uniqueKey;
//
protected $uniqueParams;
//
protected $uniqueTypes;
Methods¶
Handles method calls when a method is not implemented Handles method calls when a static method is not implementedfinal public function __construct( mixed $data = null, DiInterface $container = null, ManagerInterface $modelsManager = null );
use Phalcon\Mvc\Model;
use Phalcon\Mvc\Model\Behavior\Timestampable;
class Robots extends Model
{
public function initialize()
{
$this->addBehavior(
new Timestampable(
[
"beforeCreate" => [
"field" => "created_at",
"format" => "Y-m-d",
],
]
)
);
$this->addBehavior(
new Timestampable(
[
"beforeUpdate" => [
"field" => "updated_at",
"format" => "Y-m-d",
],
]
)
);
}
}
use Phalcon\Mvc\Model;
use Phalcon\Messages\Message as Message;
class Robots extends Model
{
public function beforeSave()
{
if ($this->name === "Peter") {
$message = new Message(
"Sorry, but a robot cannot be named Peter"
);
$this->appendMessage($message);
}
}
}
public function assign( array $data, mixed $whiteList = null, mixed $dataColumnMap = null ): ModelInterface;
$robot->assign(
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
// Assign by db row, column map needed
$robot->assign(
$dbRow,
[
"db_type" => "type",
"db_name" => "name",
"db_year" => "year",
]
);
// Allow assign only name and year
$robot->assign(
$_POST,
[
"name",
"year",
]
);
// By default assign method will use setters if exist, you can disable it by using ini_set to directly use properties
ini_set("phalcon.orm.disable_assign_setters", true);
$robot->assign(
$_POST,
[
"name",
"year",
]
);
Returned value will be a float for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the average of each group.
// What's the average price of robots?
$average = Robots::average(
[
"column" => "price",
]
);
echo "The average price is ", $average, "\n";
// What's the average price of mechanical robots?
$average = Robots::average(
[
"type = 'mechanical'",
"column" => "price",
]
);
echo "The average price of mechanical robots is ", $average, "\n";
public static function cloneResult( ModelInterface $base, array $data, int $dirtyState = int ): ModelInterface;
$robot = Phalcon\Mvc\Model::cloneResult(
new Robots(),
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
public static function cloneResultMap( mixed $base, array $data, mixed $columnMap, int $dirtyState = int, bool $keepSnapshots = null ): ModelInterface;
$robot = \Phalcon\Mvc\Model::cloneResultMap(
new Robots(),
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
Returns an integer for simple queries or a ResultsetInterface instance for when the GROUP condition is used. The results will contain the count of each group.
// How many robots are there?
$number = Robots::count();
echo "There are ", $number, "\n";
// How many mechanical robots are there?
$number = Robots::count("type = 'mechanical'");
echo "There are ", $number, " mechanical robots\n";
// Creating a new robot
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
$robot->create();
// Passing an array to create
$robot = new Robots();
$robot->assign(
[
"type" => "mechanical",
"name" => "Astro Boy",
"year" => 1952,
]
);
$robot->create();
$robot = Robots::findFirst("id=100");
$robot->delete();
$robots = Robots::find("type = 'mechanical'");
foreach ($robots as $robot) {
$robot->delete();
}
var_dump()
Query for a set of records that match the specified conditions // How many robots are there?
$robots = Robots::find();
echo "There are ", count($robots), "\n";
// How many mechanical robots are there?
$robots = Robots::find(
"type = 'mechanical'"
);
echo "There are ", count($robots), "\n";
// Get and print virtual robots ordered by name
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// Get first 100 virtual robots ordered by name
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
"limit" => 100,
]
);
foreach ($robots as $robot) {
echo $robot->name, "\n";
}
// encapsulate find it into an running transaction esp. useful for application unit-tests
// or complex business logic where we wanna control which transactions are used.
$myTransaction = new Transaction(\Phalcon\Di::getDefault());
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newRobot->save();
$resultInsideTransaction = Robot::find(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$resultOutsideTransaction = Robot::find(['name' => 'test']);
foreach ($setInsideTransaction as $robot) {
echo $robot->name, "\n";
}
foreach ($setOutsideTransaction as $robot) {
echo $robot->name, "\n";
}
// reverts all not commited changes
$myTransaction->rollback();
// creating two different transactions
$myTransaction1 = new Transaction(\Phalcon\Di::getDefault());
$myTransaction1->begin();
$myTransaction2 = new Transaction(\Phalcon\Di::getDefault());
$myTransaction2->begin();
// add a new robots
$firstNewRobot = new Robot();
$firstNewRobot->setTransaction($myTransaction1);
$firstNewRobot->assign(
[
'name' => 'first-transaction-robot',
'type' => 'mechanical',
'year' => 1944,
]
);
$firstNewRobot->save();
$secondNewRobot = new Robot();
$secondNewRobot->setTransaction($myTransaction2);
$secondNewRobot->assign(
[
'name' => 'second-transaction-robot',
'type' => 'fictional',
'year' => 1984,
]
);
$secondNewRobot->save();
// this transaction will find the robot.
$resultInFirstTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the robot.
$resultInSecondTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
]
);
// this transaction won't find the robot.
$resultInFirstTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction will find the robot.
$resultInSecondTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
]
);
$transaction1->rollback();
$transaction2->rollback();
// What's the first robot in robots table?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name;
// What's the first mechanical robot in robots table?
$robot = Robots::findFirst(
"type = 'mechanical'"
);
echo "The first mechanical robot name is ", $robot->name;
// Get first virtual robot ordered by name
$robot = Robots::findFirst(
[
"type = 'virtual'",
"order" => "name",
]
);
echo "The first virtual robot name is ", $robot->name;
// behaviour with transaction
$myTransaction = new Transaction(\Phalcon\Di::getDefault());
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newRobot->save();
$findsARobot = Robot::findFirst(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$doesNotFindARobot = Robot::findFirst(
[
'name' => 'test',
]
);
var_dump($findARobot);
var_dump($doesNotFindARobot);
$transaction->commit();
$doesFindTheRobotNow = Robot::findFirst(
[
'name' => 'test',
]
);
$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []
$robots->deleted = 'Y';
$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
if ($robot->save() === false) {
echo "Umh, We can't store robots right now ";
$messages = $robot->getMessages();
foreach ($messages as $message) {
echo $message;
}
} else {
echo "Great, a new robot was saved successfully!";
}
$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []
$robots->deleted = 'Y';
$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]
$robots->save();
print_r($robots->getChangedFields()); // []
print_r($robots->getUpdatedFields()); // ["deleted"]
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
$robot->create();
$robot->type = "hydraulic";
$hasChanged = $robot->hasChanged("type"); // returns true
$hasChanged = $robot->hasChanged(["type", "name"]); // returns true
$hasChanged = $robot->hasChanged(["type", "name"], true); // returns false
Only returns true if the records were previously fetched through the model without any additional parameters.
$robot = Robots::findFirst();
var_dump($robot->isRelationshipLoaded('robotsParts')); // false
$robotsParts = $robot->getRobotsParts(['id > 0']);
var_dump($robot->isRelationshipLoaded('robotsParts')); // false
$robotsParts = $robot->getRobotsParts(); // or $robot->robotsParts
var_dump($robot->isRelationshipLoaded('robotsParts')); // true
$robot->robotsParts = [new RobotsParts()];
var_dump($robot->isRelationshipLoaded('robotsParts')); // false
// What is the maximum robot id?
$id = Robots::maximum(
[
"column" => "id",
]
);
echo "The maximum robot id is: ", $id, "\n";
// What is the maximum id of mechanical robots?
$sum = Robots::maximum(
[
"type = 'mechanical'",
"column" => "id",
]
);
echo "The maximum robot id of mechanical robots is ", $id, "\n";
// What is the minimum robot id?
$id = Robots::minimum(
[
"column" => "id",
]
);
echo "The minimum robot id is: ", $id;
// What is the minimum id of mechanical robots?
$sum = Robots::minimum(
[
"type = 'mechanical'",
"column" => "id",
]
);
echo "The minimum robot id of mechanical robots is ", $id;
// Creating a new robot
$robot = new Robots();
$robot->type = "mechanical";
$robot->name = "Astro Boy";
$robot->year = 1952;
$robot->save();
// Updating a robot name
$robot = Robots::findFirst("id = 100");
$robot->name = "Biomass";
$robot->save();
use Phalcon\Mvc\Model\Transaction\Manager as TxManager;
use Phalcon\Mvc\Model\Transaction\Failed as TxFailed;
try {
$txManager = new TxManager();
$transaction = $txManager->get();
$robot = new Robots();
$robot->setTransaction($transaction);
$robot->name = "WALL·E";
$robot->created_at = date("Y-m-d");
if ($robot->save() === false) {
$transaction->rollback("Can't save robot");
}
$robotPart = new RobotParts();
$robotPart->setTransaction($transaction);
$robotPart->type = "head";
if ($robotPart->save() === false) {
$transaction->rollback("Robot part cannot be saved");
}
$transaction->commit();
} catch (TxFailed $e) {
echo "Failed, reason: ", $e->getMessage();
}
// How much are all robots?
$sum = Robots::sum(
[
"column" => "price",
]
);
echo "The total price of robots is ", $sum, "\n";
// How much are mechanical robots?
$sum = Robots::sum(
[
"type = 'mechanical'",
"column" => "price",
]
);
echo "The total price of mechanical robots is ", $sum, "\n";
// Updating a robot name
$robot = Robots::findFirst("id = 100");
$robot->name = "Biomass";
$robot->update();
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\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);
}
}
@todo Remove in v5.0 @deprecated Use cancelOperation()
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 Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (cascade) when deleting records Reads both "hasMany" and "hasOne" relations and checks the virtual foreign keys (restrict) when deleting recordsprotected function _doLowInsert( MetaDataInterface $metaData, AdapterInterface $connection, mixed $table, mixed $identityField ): bool;
@todo Remove in v5.0 @deprecated Use doLowInsert()
protected function _doLowUpdate( MetaDataInterface $metaData, AdapterInterface $connection, mixed $table ): bool;
@todo Remove in v5.0 @deprecated Use doLowUpdate()
Checks whether the current record already exists@todo Remove in v5.0 @deprecated Use exists()
Returns related records defined relations depending on the method name. Returns false if the relation is non-existent.@todo Remove in v5.0 @deprecated Use getRelatedRecords()
protected $static function _groupResult( string $functionName, string $alias, mixed $parameters ): ResultsetInterface;
@todo Remove in v5.0 @deprecated Use groupResult()
Check for, and attempt to use, possible setter. Executes internal events after save a record@todo Remove in v5.0 @deprecated Use postSave()
Save the related records assigned in the has-one/has-many relations@todo Remove in v5.0 @deprecated Use postSaveRelatedRecords()
protected function _preSave( MetaDataInterface $metaData, bool $exists, mixed $identityField ): bool;
@todo Remove in v5.0 @deprecated Use preSave()
Saves related records that must be stored prior to save the master record@todo Remove in v5.0 @deprecated Use preSaveRelatedRecords()
Sets a list of attributes that must be skipped from the generated UPDATE statementclass Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->allowEmptyStringValues(
[
"name",
]
);
}
}
protected function belongsTo( mixed $fields, string $referenceModel, mixed $referencedFields, mixed $options = null ): Relation;
class RobotsParts extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->belongsTo(
"robots_id",
Robots::class,
"id"
);
}
}
protected function doLowInsert( MetaDataInterface $metaData, AdapterInterface $connection, mixed $table, mixed $identityField ): bool;
protected function doLowUpdate( MetaDataInterface $metaData, AdapterInterface $connection, mixed $table ): bool;
protected $static function groupResult( string $functionName, string $alias, mixed $parameters ): ResultsetInterface;
protected function hasMany( mixed $fields, string $referenceModel, mixed $referencedFields, mixed $options = null ): Relation;
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasMany(
"id",
RobotsParts::class,
"robots_id"
);
}
}
protected function hasManyToMany( mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referenceModel, mixed $referencedFields, mixed $options = null ): Relation;
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
// Setup a many-to-many relation to Parts through RobotsParts
$this->hasManyToMany(
"id",
RobotsParts::class,
"robots_id",
"parts_id",
Parts::class,
"id",
);
}
}
protected function hasOne( mixed $fields, string $referenceModel, mixed $referencedFields, mixed $options = null ): Relation;
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->hasOne(
"id",
RobotsDescription::class,
"robots_id"
);
}
}
protected function hasOneThrough( mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referenceModel, mixed $referencedFields, mixed $options = null ): Relation;
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
// Setup a 1-1 relation to one item from Parts through RobotsParts
$this->hasOneThrough(
"id",
RobotsParts::class,
"robots_id",
"parts_id",
Parts::class,
"id",
);
}
}
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->keepSnapshots(true);
}
}
protected function preSave( MetaDataInterface $metaData, bool $exists, mixed $identityField ): bool;
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->skipAttributes(
[
"price",
]
);
}
}
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->skipAttributesOnCreate(
[
"created_at",
]
);
}
}
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->skipAttributesOnUpdate(
[
"modified_in",
]
);
}
}
use Phalcon\Mvc\Model;
class Robots extends Model
{
public function initialize()
{
$this->useDynamicUpdate(true);
}
}
use Phalcon\Mvc\Model;
use Phalcon\Validation;
use Phalcon\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\Model\Behavior ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
BehaviorInterface
Phalcon\Mvc\Model\Behavior
This is an optional base class for ORM behaviors
Properties¶
Methods¶
Phalcon\Mvc\Model\Behavior Acts as fallbacks when a missing method is called on the model This method receives the notifications from the EventsManager Returns the behavior options related to an event Checks whether the behavior must take action on certain eventMvc\Model\Behavior\SoftDelete¶
-
Namespace
Phalcon\Mvc\Model\Behavior
-
Uses
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Behavior
Phalcon\Mvc\Model\Exception
-
Extends
Behavior
-
Implements
Phalcon\Mvc\Model\Behavior\SoftDelete
Instead of permanently delete a record it marks the record as deleted changing the value of a flag column
Methods¶
Listens for notifications from the models managerMvc\Model\Behavior\Timestampable¶
-
Namespace
Phalcon\Mvc\Model\Behavior
-
Uses
Closure
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Behavior
Phalcon\Mvc\Model\Exception
-
Extends
Behavior
-
Implements
Phalcon\Mvc\Model\Behavior\Timestampable
Allows to automatically update a model’s attribute saving the datetime when a record is created or updated
Methods¶
Listens for notifications from the models managerMvc\Model\BehaviorInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\BehaviorInterface
Interface for Phalcon\Mvc\Model\Behavior
Methods¶
Calls a method when it's missing in the model This method receives the notifications from the EventsManagerMvc\Model\Binder¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Closure
Phalcon\Cache\Adapter\AdapterInterface
Phalcon\Mvc\Controller\BindModelInterface
Phalcon\Mvc\Model\Binder\BindableInterface
ReflectionFunction
ReflectionMethod
-
Extends
-
Implements
BinderInterface
Phalcon\Mvc\Model\Binder
This is an class for binding models into params for handler
Properties¶
/**
* Array for storing active bound models
*
* @var array
*/
protected $boundModels;
/**
* Cache object used for caching parameters for model binding
*/
protected $cache;
/**
* Internal cache for caching parameters for model binding during request
*/
protected $internalCache;
/**
* Array for original values
*/
protected $originalValues;
Methods¶
Phalcon\Mvc\Model\Binder constructorpublic function bindToHandler( object $handler, array $params, string $cacheKey, string $methodName = null ): array;
protected function getParamsFromReflection( object $handler, array $params, string $cacheKey, string $methodName ): array;
Mvc\Model\Binder\BindableInterface ¶
-
Namespace
Phalcon\Mvc\Model\Binder
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\Model\Binder\BindableInterface
Interface for bindable classes
Methods¶
Return the model name or models names and parameters keys associated with this classMvc\Model\BinderInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Cache\Adapter\AdapterInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\BinderInterface
Interface for Phalcon\Mvc\Model\Binder
Methods¶
public function bindToHandler( object $handler, array $params, string $cacheKey, string $methodName = null ): array;
Mvc\Model\Criteria¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Db\Column
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\Model\Query\BuilderInterface
-
Extends
-
Implements
CriteriaInterface
InjectionAwareInterface
Phalcon\Mvc\Model\Criteria
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.
$robots = Robots::query()
->where("type = :type:")
->andWhere("year < 2000")
->bind(["type" => "mechanical"])
->limit(5, 10)
->orderBy("name")
->execute();
Properties¶
//
protected $bindParams;
//
protected $bindTypes;
//
protected $hiddenParamNumber = 0;
//
protected $model;
//
protected $params;
Methods¶
public function andWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
$builder = Robots::query()
->where("type = :type:")
->bind(["type" => "mechanical"])
->createBuilder();
public static function fromInput( DiInterface $container, string $modelName, array $data, string $operator = string ): CriteriaInterface;
- 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
public function innerJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
$criteria->innerJoin(
Robots::class
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id"
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
public function join( string $model, mixed $conditions = null, mixed $alias = null, mixed $type = null ): CriteriaInterface;
$criteria->join(
Robots::class
);
$criteria->join(
Robots::class,
"r.id = RobotsParts.robots_id"
);
$criteria->join(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
$criteria->join(
Robots::class,
"r.id = RobotsParts.robots_id",
"r",
"LEFT"
);
public function leftJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function orWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
public function rightJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function where( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
Mvc\Model\CriteriaInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Di\DiInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\CriteriaInterface
Interface for Phalcon\Mvc\Model\Criteria
Methods¶
public function andWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
- 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
public function innerJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
$criteria->innerJoin(
Robots::class
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id"
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
public function leftJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function orWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
public function rightJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function where( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
Mvc\Model\Exception¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
-
Extends
\Exception
-
Implements
Phalcon\Mvc\Model\Exception
Exceptions thrown in Phalcon\Mvc\Model* classes will use this class
Mvc\Model\Manager¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Events\EventsAwareInterface
Phalcon\Events\ManagerInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Query\Builder
Phalcon\Mvc\Model\Query\BuilderInterface
Phalcon\Mvc\Model\Query\StatusInterface
ReflectionClass
ReflectionProperty
-
Extends
-
Implements
EventsAwareInterface
InjectionAwareInterface
ManagerInterface
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.
use Phalcon\Di;
use Phalcon\Mvc\Model\Manager as ModelsManager;
$di = new Di();
$di->set(
"modelsManager",
function() {
return new ModelsManager();
}
);
$robot = new Robots($di);
Properties¶
//
protected $aliases;
/**
* Models' behaviors
*/
protected $behaviors;
/**
* Belongs to relations
*/
protected $belongsTo;
/**
* All the relationships by model
*/
protected $belongsToSingle;
//
protected $container;
//
protected $customEventsManager;
/**
* Does the model use dynamic update, instead of updating all rows?
*/
protected $dynamicUpdate;
//
protected $eventsManager;
/**
* Has many relations
*/
protected $hasMany;
/**
* Has many relations by model
*/
protected $hasManySingle;
/**
* Has many-Through relations
*/
protected $hasManyToMany;
/**
* Has many-Through relations by model
*/
protected $hasManyToManySingle;
/**
* Has one relations
*/
protected $hasOne;
/**
* Has one relations by model
*/
protected $hasOneSingle;
/**
* Has one through relations
*/
protected $hasOneThrough;
/**
* Has one through relations by model
*/
protected $hasOneThroughSingle;
/**
* Mark initialized models
*/
protected $initialized;
//
protected $keepSnapshots;
/**
* Last model initialized
*/
protected $lastInitialized;
/**
* Last query created/executed
*/
protected $lastQuery;
//
protected $modelVisibility;
//
protected $prefix = ;
//
protected $readConnectionServices;
//
protected $sources;
//
protected $schemas;
//
protected $writeConnectionServices;
/**
* Stores a list of reusable instances
*/
protected $reusable;
Methods¶
Destroys the current PHQL cache Returns the connection service name used to read or write data related to a model depending on the connection services@todo Remove in v5.0 @deprecated Use getConnectionService()
Binds a behavior to a modelpublic function addBelongsTo( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasMany( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasManyToMany( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasOne( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasOneThrough( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function executeQuery( string $phql, mixed $placeholders = null, mixed $types = null ): mixed;
$model = new Robots();
$manager = $model->getModelsManager();
// \Phalcon\Mvc\Model\Resultset\Simple
$manager->executeQuery('SELECTFROM Robots');
// \Phalcon\Mvc\Model\Resultset\Complex
$manager->executeQuery('SELECT COUNT(type) FROM Robots GROUP BY type');
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('INSERT INTO Robots (id) VALUES (1)');
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('UPDATE Robots SET id = 0 WHERE id = :id:', ['id' => 1]);
// \Phalcon\Mvc\Model\Query\StatusInterface
$manager->executeQuery('DELETE FROM Robots WHERE id = :id:', ['id' => 1]);
public function getBelongsToRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
public function getHasManyRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
public function getHasOneRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ModelInterface | bool;
public function getRelationRecords( RelationInterface $relation, ModelInterface $record, mixed $parameters = null, string $method = null );
public function setCustomEventsManager( ModelInterface $model, EventsManagerInterface $eventsManager ): void;
use Phalcon\Mvc\Model\Manager;
$di->set(
"modelsManager",
function () {
$modelsManager = new Manager();
$modelsManager->setModelPrefix("wp_");
return $modelsManager;
}
);
$robots = new Robots();
echo $robots->getSource(); // wp_robots
public function setWriteConnectionService( ModelInterface $model, string $connectionService ): void;
protected function _getConnection( ModelInterface $model, mixed $connectionServices ): AdapterInterface;
@todo Remove in v5.0 @deprecated Use getConnection()
Merge two arrays of find parametersprotected function getConnection( ModelInterface $model, mixed $connectionServices ): AdapterInterface;
Mvc\Model\ManagerInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Query\BuilderInterface
Phalcon\Mvc\Model\Query\StatusInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\ManagerInterface
Interface for Phalcon\Mvc\Model\Manager
Methods¶
Binds a behavior to a modelpublic function addBelongsTo( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasMany( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasManyToMany( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasOne( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function addHasOneThrough( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, mixed $options = null ): RelationInterface;
public function executeQuery( string $phql, mixed $placeholders = null, mixed $types = null ): mixed;
public function getBelongsToRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
public function getHasManyRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
public function getHasOneRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ModelInterface | bool;
public function getRelationRecords( RelationInterface $relation, ModelInterface $record, mixed $parameters = null, string $method = null );
Mvc\Model\MetaData ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Cache\Adapter\AdapterInterface
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\MetaData\Strategy\Introspection
Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
-
Extends
-
Implements
InjectionAwareInterface
MetaDataInterface
Phalcon\Mvc\Model\MetaData
Because Phalcon\Mvc\Model requires meta-data like field names, data types, primary keys, etc. This component collect them and store for further querying by Phalcon\Mvc\Model. Phalcon\Mvc\Model\MetaData can also use adapters to store temporarily or permanently the meta-data.
A standard Phalcon\Mvc\Model\MetaData can be used to query model attributes:
$metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
$attributes = $metaData->getAttributes(
new Robots()
);
print_r($attributes);
Constants¶
const MODELS_ATTRIBUTES = 0;
const MODELS_AUTOMATIC_DEFAULT_INSERT = 10;
const MODELS_AUTOMATIC_DEFAULT_UPDATE = 11;
const MODELS_COLUMN_MAP = 0;
const MODELS_DATA_TYPES = 4;
const MODELS_DATA_TYPES_BIND = 9;
const MODELS_DATA_TYPES_NUMERIC = 5;
const MODELS_DATE_AT = 6;
const MODELS_DATE_IN = 7;
const MODELS_DEFAULT_VALUES = 12;
const MODELS_EMPTY_STRING_VALUES = 13;
const MODELS_IDENTITY_COLUMN = 8;
const MODELS_NON_PRIMARY_KEY = 2;
const MODELS_NOT_NULL = 3;
const MODELS_PRIMARY_KEY = 1;
const MODELS_REVERSE_COLUMN_MAP = 1;
Properties¶
/**
* @var CacheAdapterInterface
*/
protected $adapter;
//
protected $columnMap;
//
protected $container;
//
protected $metaData;
//
protected $strategy;
Methods¶
Returns table attributes names (fields) Returns attributes that must be ignored from the INSERT SQL generation Returns attributes that must be ignored from the UPDATE SQL generation Returns attributes and their bind data types Returns the column map if any Returns the DependencyInjector container Returns attributes and their data types Returns attributes which types are numerical Returns attributes (which have default values) and their default values Returns attributes allow empty strings Returns the name of identity field (if one is present) Returns an array of fields which are not part of the primary key Returns an array of not null attributes Returns an array of fields which are part of the primary key Returns the reverse column map if any Return the strategy to obtain the meta-data Check if a model has certain attribute Checks if the internal meta-data container is empty Reads metadata from the adapter Reads the ordered/reversed column map for certain model Reads column-map information for certain model using a MODEL_* constant Reads the complete meta-data for certain model Reads meta-data for certain model Resets internal meta-data in order to regenerate it Set the attributes that must be ignored from the INSERT SQL generation Set the attributes that must be ignored from the UPDATE SQL generation Sets the DependencyInjector container Set the attributes that allow empty string values Set the meta-data extraction strategy Writes the metadata to adapter Writes meta-data for certain model using a MODEL_* constantprint_r(
$metaData->writeColumnMapIndex(
new Robots(),
MetaData::MODELS_REVERSE_COLUMN_MAP,
[
"leName" => "name",
]
)
);
final protected function initialize( ModelInterface $model, mixed $key, mixed $table, mixed $schema );
Mvc\Model\MetaData\Apcu¶
-
Namespace
Phalcon\Mvc\Model\MetaData
-
Uses
Phalcon\Helper\Arr
Phalcon\Mvc\Model\MetaData
Phalcon\Mvc\Model\Exception
Phalcon\Cache\AdapterFactory
-
Extends
MetaData
-
Implements
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,
]
);
Methods¶
Phalcon\Mvc\Model\MetaData\Apcu constructorMvc\Model\MetaData\Libmemcached¶
-
Namespace
Phalcon\Mvc\Model\MetaData
-
Uses
Phalcon\Helper\Arr
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
Phalcon\Cache\AdapterFactory
-
Extends
MetaData
-
Implements
Phalcon\Mvc\Model\MetaData\Libmemcached
Stores model meta-data in the Memcache.
By default meta-data is stored for 48 hours (172800 seconds)
Methods¶
Phalcon\Mvc\Model\MetaData\Libmemcached constructor Flush Memcache data and resets internal meta-data in order to regenerate itMvc\Model\MetaData\Memory¶
-
Namespace
Phalcon\Mvc\Model\MetaData
-
Uses
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
Extends
MetaData
-
Implements
Phalcon\Mvc\Model\MetaData\Memory
Stores model meta-data in memory. Data will be erased when the request finishes
Methods¶
Phalcon\Mvc\Model\MetaData\Memory constructor Reads the meta-data from temporal memory Writes the meta-data to temporal memoryMvc\Model\MetaData\Redis¶
-
Namespace
Phalcon\Mvc\Model\MetaData
-
Uses
Phalcon\Cache\AdapterFactory
Phalcon\Helper\Arr
Phalcon\Mvc\Model\MetaData
-
Extends
MetaData
-
Implements
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,
]
);
Methods¶
Phalcon\Mvc\Model\MetaData\Redis constructor Flush Redis data and resets internal meta-data in order to regenerate itMvc\Model\MetaData\Strategy\Annotations¶
-
Namespace
Phalcon\Mvc\Model\MetaData\Strategy
-
Uses
Phalcon\Db\Column
Phalcon\Di\DiInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
Extends
-
Implements
StrategyInterface
This file is part of the Phalcon Framework.
(c) Phalcon Team team@phalcon.io
For the full copyright and license information, please view the LICENSE.txt file that was distributed with this source code.
Methods¶
Read the model's column map, this can't be inferred The meta-data is obtained by reading the column descriptions from the database information schemaMvc\Model\MetaData\Strategy\Introspection¶
-
Namespace
Phalcon\Mvc\Model\MetaData\Strategy
-
Uses
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Db\Column
Phalcon\Di\DiInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
Extends
-
Implements
StrategyInterface
Phalcon\Mvc\Model\MetaData\Strategy\Introspection
Queries the table meta-data in order to introspect the model's metadata
Methods¶
Read the model's column map, this can't be inferred The meta-data is obtained by reading the column descriptions from the database information schemaMvc\Model\MetaData\Strategy\StrategyInterface ¶
-
Namespace
Phalcon\Mvc\Model\MetaData\Strategy
-
Uses
Phalcon\Di\DiInterface
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
This file is part of the Phalcon Framework.
(c) Phalcon Team team@phalcon.io
For the full copyright and license information, please view the LICENSE.txt file that was distributed with this source code.
Methods¶
Read the model's column map, this can't be inferred@todo Not implemented
The meta-data is obtained by reading the column descriptions from the database information schemaMvc\Model\MetaData\Stream¶
-
Namespace
Phalcon\Mvc\Model\MetaData
-
Uses
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
Extends
MetaData
-
Implements
Phalcon\Mvc\Model\MetaData\Stream
Stores model meta-data in PHP files.
Properties¶
Methods¶
Phalcon\Mvc\Model\MetaData\Files constructor Reads meta-data from files Writes the meta-data to filesMvc\Model\MetaDataInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\MetaDataInterface
Interface for Phalcon\Mvc\Model\MetaData
Methods¶
Returns table attributes names (fields) Returns attributes that must be ignored from the INSERT SQL generation Returns attributes that must be ignored from the UPDATE SQL generation Returns attributes and their bind data types Returns the column map if any Returns attributes and their data types Returns attributes which types are numerical Returns attributes (which have default values) and their default values Returns attributes allow empty strings Returns the name of identity field (if one is present) Returns an array of fields which are not part of the primary key Returns an array of not null attributes Returns an array of fields which are part of the primary key Returns the reverse column map if any Return the strategy to obtain the meta-data Check if a model has certain attribute Checks if the internal meta-data container is empty Reads meta-data from the adapter Reads the ordered/reversed column map for certain model Reads column-map information for certain model using a MODEL_* constant Reads meta-data for certain model Reads meta-data for certain model using a MODEL_* constant Resets internal meta-data in order to regenerate it Set the attributes that must be ignored from the INSERT SQL generation Set the attributes that must be ignored from the UPDATE SQL generation Set the attributes that allow empty string values Set the meta-data extraction strategy Writes meta-data to the adapter Writes meta-data for certain model using a MODEL_* constantMvc\Model\Query¶
-
Namespace
Phalcon\Mvc\Model
-
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\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
-
Extends
-
Implements
InjectionAwareInterface
QueryInterface
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 = 'SELECTFROM robot';
$myTransaction = new Transaction($di);
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->type = "mechanical";
$newRobot->name = "Astro Boy";
$newRobot->year = 1952;
$newRobot->save();
$queryWithTransaction = new Query($phql, $di);
$queryWithTransaction->setTransaction($myTransaction);
$resultWithEntries = $queryWithTransaction->execute();
$queryWithOutTransaction = new Query($phql, $di);
$resultWithOutEntries = $queryWithTransaction->execute();
Constants¶
Properties¶
//
protected $ast;
//
protected $bindParams;
//
protected $bindTypes;
//
protected $cache;
//
protected $cacheOptions;
//
protected $container;
//
protected $enableImplicitJoins;
//
protected $intermediate;
//
protected $manager;
//
protected $metaData;
//
protected $models;
//
protected $modelsInstances;
//
protected $nestingLevel = -1;
//
protected $phql;
//
protected $sharedLock;
//
protected $sqlAliases;
//
protected $sqlAliasesModels;
//
protected $sqlAliasesModelsInstances;
//
protected $sqlColumnAliases;
//
protected $sqlModelsAliases;
//
protected $type;
//
protected $uniqueRow;
//
static protected $_irPhqlCache;
/**
* 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 $_transaction;
Methods¶
public function __construct( string $phql = null, DiInterface $container = null, array $options = [] );
final protected function _executeDelete( array $intermediate, array $bindParams, array $bindTypes ): StatusInterface;
final protected function _executeInsert( array $intermediate, array $bindParams, array $bindTypes ): StatusInterface;
final protected function _executeSelect( array $intermediate, array $bindParams, array $bindTypes, bool $simulate = bool ): ResultsetInterface | array;
final protected function _executeUpdate( array $intermediate, array $bindParams, array $bindTypes ): StatusInterface;
final protected function _getMultiJoin( string $joinType, mixed $joinSource, string $modelAlias, string $joinAlias, RelationInterface $relation ): array;
final protected function _getRelatedRecords( ModelInterface $model, array $intermediate, array $bindParams, array $bindTypes ): ResultsetInterface;
@todo Remove in v5.0 @deprecated Use getRelatedRecords()
Resolves a column from its intermediate representation into an array used to determine if the resultset produced is simple or complexfinal protected function _getSingleJoin( string $joinType, mixed $joinSource, string $modelAlias, string $joinAlias, RelationInterface $relation ): array;
protected function getReadConnection( ModelInterface $model, array $intermediate = null, array $bindParams = [], array $bindTypes = [] ): AdapterInterface;
final protected function getRelatedRecords( ModelInterface $model, array $intermediate, array $bindParams, array $bindTypes ): ResultsetInterface;
protected function getWriteConnection( ModelInterface $model, array $intermediate = null, array $bindParams = [], array $bindTypes = [] ): AdapterInterface;
Mvc\Model\Query\Builder¶
-
Namespace
Phalcon\Mvc\Model\Query
-
Uses
Phalcon\Db\Column
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\QueryInterface
-
Extends
-
Implements
BuilderInterface
InjectionAwareInterface
Phalcon\Mvc\Model\Query\Builder
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);
Properties¶
//
protected $bindParams;
//
protected $bindTypes;
//
protected $columns;
//
protected $conditions;
//
protected $container;
//
protected $distinct;
//
protected $forUpdate;
/**
* @var array
*/
protected $group;
//
protected $having;
//
protected $hiddenParamNumber = 0;
//
protected $joins;
//
protected $limit;
/**
* @var array|string
*/
protected $models;
//
protected $offset;
//
protected $order;
//
protected $sharedLock;
Methods¶
Phalcon\Mvc\Model\Query\Builder constructor Add a model to take part of the query// Load data from models Robots
$builder->addFrom(
Robots::class
);
// Load data from model 'Robots' using 'r' as alias in PHQL
$builder->addFrom(
Robots::class,
"r"
);
public function andHaving( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->andHaving("SUM(Robots.price) > 0");
$builder->andHaving(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function andWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->andWhere("name = 'Peter'");
$builder->andWhere(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
public function betweenHaving( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
public function betweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
Sets the columns to be queried. The columns can be either a string
or an array
. The string 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 element. If a key is defined in our 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",
]
);
$builder->from(
Robots::class
);
$builder->from(
[
Robots::class,
RobotsParts::class,
]
);
$builder->from(
[
"r" => Robots::class,
"rp" => RobotsParts::class,
]
);
public function having( mixed $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->having("SUM(Robots.price) > 0");
$builder->having(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function inHaving( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
public function inWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
public function innerJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
// Inner Join model 'Robots' with automatic conditions and alias
$builder->innerJoin(
Robots::class
);
// Inner Join model 'Robots' specifying conditions
$builder->innerJoin(
Robots::class,
"Robots.id = RobotsParts.robots_id"
);
// Inner Join model 'Robots' specifying conditions and alias
$builder->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
public function join( string $model, string $conditions = null, string $alias = null, string $type = null ): BuilderInterface;
// Inner Join model 'Robots' with automatic conditions and alias
$builder->join(
Robots::class
);
// Inner Join model 'Robots' specifying conditions
$builder->join(
Robots::class,
"Robots.id = RobotsParts.robots_id"
);
// Inner Join model 'Robots' specifying conditions and alias
$builder->join(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
// Left Join model 'Robots' specifying conditions, alias and type of join
$builder->join(
Robots::class,
"r.id = RobotsParts.robots_id",
"r",
"LEFT"
);
public function leftJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
public function notBetweenHaving( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
public function notBetweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
public function notInHaving( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
public function notInWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
public function orHaving( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->orHaving("SUM(Robots.price) > 0");
$builder->orHaving(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function orWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->orWhere("name = 'Peter'");
$builder->orWhere(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
$builder->orderBy("Robots.name");
$builder->orderBy(["1", "Robots.name"]);
$builder->orderBy(["Robots.name DESC"]);
public function rightJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
public function where( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->where(100);
$builder->where("name = 'Peter'");
$builder->where(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
protected function conditionBetween( string $clause, string $operator, string $expr, mixed $minimum, mixed $maximum ): BuilderInterface;
protected function conditionIn( string $clause, string $operator, string $expr, array $values ): BuilderInterface;
protected function conditionNotBetween( string $clause, string $operator, string $expr, mixed $minimum, mixed $maximum ): BuilderInterface;
protected function conditionNotIn( string $clause, string $operator, string $expr, array $values ): BuilderInterface;
Mvc\Model\Query\BuilderInterface ¶
-
Namespace
Phalcon\Mvc\Model\Query
-
Uses
Phalcon\Mvc\Model\QueryInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\Query\BuilderInterface
Interface for Phalcon\Mvc\Model\Query\Builder
Constants¶
Methods¶
Add a model to take part of the querypublic function andWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
public function betweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
string
or an array
. The string 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 element. If a key is defined in our 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",
]
);
public function inWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
public function innerJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
public function join( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
public function leftJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
public function notBetweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
public function notInWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
public function orWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
public function rightJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
public function where( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
Mvc\Model\Query\Lang ¶
-
Namespace
Phalcon\Mvc\Model\Query
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\Model\Query\Lang
PHQL is implemented as a parser (written in C) that translates syntax in that of the target RDBMS. It allows Phalcon to offer a unified SQL language to the developer, while internally doing all the work of translating PHQL instructions to the most optimal SQL instructions depending on the RDBMS type associated with a model.
To achieve the highest performance possible, we wrote a parser that uses the same technology as SQLite. This technology provides a small in-memory parser with a very low memory footprint that is also thread-safe.
use Phalcon\Mvc\Model\Query\Lang;
$intermediate = Lang::parsePHQL(
"SELECT r.* FROM Robots r LIMIT 10"
);
Methods¶
Parses a PHQL statement returning an intermediate representation (IR)Mvc\Model\Query\Status¶
-
Namespace
Phalcon\Mvc\Model\Query
-
Uses
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
StatusInterface
Phalcon\Mvc\Model\Query\Status
This class represents the status returned by a PHQL statement like INSERT, UPDATE or DELETE. It offers context information and the related messages produced by the model which finally executes the operations when it fails
$phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";
$status = $app->modelsManager->executeQuery(
$phql,
[
"id" => 100,
"name" => "Astroy Boy",
"type" => "mechanical",
"year" => 1959,
]
);
// Check if the update was successful
if ($status->success()) {
echo "OK";
}
Properties¶
Methods¶
Phalcon\Mvc\Model\Query\Status Returns the messages produced because of a failed operation Returns the model that executed the action Allows to check if the executed operation was successfulMvc\Model\Query\StatusInterface ¶
-
Namespace
Phalcon\Mvc\Model\Query
-
Uses
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\Query\StatusInterface
Interface for Phalcon\Mvc\Model\Query\Status
Methods¶
Returns the messages produced by an operation failed Returns the model which executed the action Allows to check if the executed operation was successfulMvc\Model\QueryInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\QueryInterface
Interface for Phalcon\Mvc\Model\Query
Methods¶
Sets the cache parameters of the query Executes a parsed PHQL statement Returns default bind params Returns default bind types Returns the current cache options Executes the query returning the first result Returns the SQL to be generated by the internal PHQL (only works in SELECT statements) Check if the query is programmed to get only the first row in the resultset Parses the intermediate code produced by Phalcon\Mvc\Model\Query\Lang generating another intermediate representation that could be executed by Phalcon\Mvc\Model\Query Set default bind parameters Set default bind parameters Set SHARED LOCK clause Tells to the query if only the first row in the resultset must be returnedMvc\Model\Relation¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
-
Extends
-
Implements
RelationInterface
Phalcon\Mvc\Model\Relation
This class represents a relationship between two models
Constants¶
const ACTION_CASCADE = 2;
const ACTION_RESTRICT = 1;
const BELONGS_TO = 0;
const HAS_MANY = 2;
const HAS_MANY_THROUGH = 4;
const HAS_ONE = 1;
const HAS_ONE_THROUGH = 3;
const NO_ACTION = 0;
Properties¶
//
protected $fields;
//
protected $intermediateFields;
//
protected $intermediateModel;
//
protected $intermediateReferencedFields;
//
protected $options;
//
protected $referencedFields;
//
protected $referencedModel;
//
protected $type;
Methods¶
public function __construct( int $type, string $referencedModel, mixed $fields, mixed $referencedFields, array $options = [] );
public function setIntermediateRelation( mixed $intermediateFields, string $intermediateModel, mixed $intermediateReferencedFields );
Mvc\Model\RelationInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\Model\RelationInterface
Interface for Phalcon\Mvc\Model\Relation
Methods¶
Returns the fields Returns the foreign key configuration Gets the intermediate fields for has-*-through relations Gets the intermediate model for has-*-through relations Gets the intermediate referenced fields for has-*-through relations Returns an option by the specified name If the option doesn't exist null is returned Returns the options Returns parameters that must be always used when the related records are obtained Returns the referenced fields Returns the referenced model Returns the relations type Check whether the relation act as a foreign key Check if records returned by getting belongs-to/has-many are implicitly cached during the current request Check whether the relation is a 'many-to-many' relation or notpublic function setIntermediateRelation( mixed $intermediateFields, string $intermediateModel, mixed $intermediateReferencedFields );
Mvc\Model\ResultInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\ResultInterface
All single objects passed as base objects to Resultsets must implement this interface
Methods¶
Sets the object's stateMvc\Model\Resultset ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
ArrayAccess
Closure
Countable
Iterator
JsonSerializable
Phalcon\Cache\CacheInterface
Phalcon\Db\Enum
Phalcon\Messages\MessageInterface
Phalcon\Mvc\Model
Phalcon\Mvc\ModelInterface
Phalcon\Storage\Serializer\SerializerInterface
SeekableIterator
Serializable
-
Extends
-
Implements
ArrayAccess
Countable
Iterator
JsonSerializable
ResultsetInterface
SeekableIterator
Serializable
Phalcon\Mvc\Model\Resultset
This component allows to Phalcon\Mvc\Model returns large resultsets with the minimum memory consumption Resultsets can be traversed using a standard foreach or a while statement. If a resultset is serialized it will dump all the rows into a big array. Then unserialize will retrieve the rows as they were before serializing.
// Using a standard foreach
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($robots as robot) {
echo robot->name, "\n";
}
// Using a while
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
$robots->rewind();
while ($robots->valid()) {
$robot = $robots->current();
echo $robot->name, "\n";
$robots->next();
}
Constants¶
const HYDRATE_ARRAYS = 1;
const HYDRATE_OBJECTS = 2;
const HYDRATE_RECORDS = 0;
const TYPE_RESULT_FULL = 0;
const TYPE_RESULT_PARTIAL = 1;
Properties¶
//
protected $activeRow;
//
protected $cache;
//
protected $count = 0;
//
protected $errorMessages;
//
protected $hydrateMode = 0;
//
protected $isFresh = true;
//
protected $pointer = 0;
//
protected $row;
//
protected $rows;
/**
* Phalcon\Db\ResultInterface or false for empty resultset
*/
protected $result;
Methods¶
Phalcon\Mvc\Model\Resultset constructor Counts how many rows are in the resultset Deletes every record in the resultset Filters a resultset returning only those the developer requires Returns the associated cache for the resultset Get first row in the resultset$model = new Robots();
$manager = $model->getModelsManager();
// \Robots
$manager->createQuery('SELECTFROM Robots')
->execute()
->getFirst();
// \Phalcon\Mvc\Model\Row
$manager->createQuery('SELECT r.id FROM Robots AS r')
->execute()
->getFirst();
// NULL
$manager->createQuery('SELECT r.id FROM Robots AS r WHERE r.name = "NON-EXISTENT"')
->execute()
->getFirst();
Mvc\Model\Resultset\Complex¶
-
Namespace
Phalcon\Mvc\Model\Resultset
-
Uses
Phalcon\Db\ResultInterface
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Mvc\Model
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\Resultset
Phalcon\Mvc\Model\ResultsetInterface
Phalcon\Mvc\Model\Row
Phalcon\Storage\Serializer\SerializerInterface
stdClass
-
Extends
Resultset
-
Implements
ResultsetInterface
Phalcon\Mvc\Model\Resultset\Complex
Complex resultsets may include complete objects and scalar values. This class builds every complex row as it is required
Properties¶
//
protected $columnTypes;
/**
* Unserialised result-set hydrated all rows already. unserialise() sets
* disableHydration to true
*/
protected $disableHydration = false;
Methods¶
public function __construct( mixed $columnTypes, ResultInterface $result = null, AdapterInterface $cache = null );
Mvc\Model\Resultset\Simple¶
-
Namespace
Phalcon\Mvc\Model\Resultset
-
Uses
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Mvc\Model
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\Resultset
Phalcon\Mvc\Model\Row
Phalcon\Storage\Serializer\SerializerInterface
-
Extends
Resultset
-
Implements
Phalcon\Mvc\Model\Resultset\Simple
Simple resultsets only contains a complete objects This class builds every complete object as it is required
Properties¶
Methods¶
public function __construct( mixed $columnMap, mixed $model, mixed $result, AdapterInterface $cache = null, bool $keepSnapshots = null );
Mvc\Model\ResultsetInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Closure
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\ResultsetInterface
Interface for Phalcon\Mvc\Model\Resultset
Methods¶
Deletes every record in the resultset Filters a resultset returning only those the developer requires Returns the associated cache for the resultset Get first row in the resultset Returns the current hydration mode Get last row in the resultset Returns the error messages produced by a batch operation Returns the internal type of data retrieval that the resultset is using Tell if the resultset if fresh or an old one cached Sets the hydration mode in the resultset Set if the resultset is fresh or an old one cached 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. Updates every record in the resultsetMvc\Model\Row¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
ArrayAccess
JsonSerializable
Phalcon\Mvc\EntityInterface
Phalcon\Mvc\ModelInterface
-
Extends
-
Implements
ArrayAccess
EntityInterface
JsonSerializable
ResultInterface
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].
Methods¶
Serializes the object for json_encode Checks whether offset exists in the row Gets a record in a specific position of the row Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface Rows cannot be changed. It has only been implemented to meet the definition of the ArrayAccess interface Reads an attribute value by its name Set the current object's state Returns the instance as an array representation Writes an attribute value by its nameMvc\Model\Transaction¶
-
Namespace
Phalcon\Mvc\Model
-
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
-
Extends
-
Implements
TransactionInterface
Phalcon\Mvc\Model\Transaction
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. Phalcon\Transaction is intended to be used with Phalcon_Model_Base. Phalcon Transactions should be created using Phalcon\Transaction\Manager.
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$manager = new Manager();
$transaction = $manager->get();
$robot = new Robots();
$robot->setTransaction($transaction);
$robot->name = "WALL·E";
$robot->created_at = date("Y-m-d");
if ($robot->save() === false) {
$transaction->rollback("Can't save robot");
}
$robotPart = new RobotParts();
$robotPart->setTransaction($transaction);
$robotPart->type = "head";
if ($robotPart->save() === false) {
$transaction->rollback("Can't save robot part");
}
$transaction->commit();
} catch(Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
Properties¶
//
protected $activeTransaction = false;
//
protected $connection;
//
protected $isNewTransaction = true;
//
protected $manager;
//
protected $messages;
//
protected $rollbackRecord;
//
protected $rollbackOnAbort = false;
//
protected $rollbackThrowException = false;
Methods¶
public function __construct( DiInterface $container, bool $autoBegin = bool, string $service = string );
public function rollback( string $rollbackMessage = null, ModelInterface $rollbackRecord = null ): bool;
Mvc\Model\Transaction\Exception¶
-
Namespace
Phalcon\Mvc\Model\Transaction
-
Uses
-
Extends
\Phalcon\Mvc\Model\Exception
-
Implements
Phalcon\Mvc\Model\Transaction\Exception
Exceptions thrown in Phalcon\Mvc\Model\Transaction will use this class
Mvc\Model\Transaction\Failed¶
-
Namespace
Phalcon\Mvc\Model\Transaction
-
Uses
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
Extends
Exception
-
Implements
Phalcon\Mvc\Model\Transaction\Failed
This class will be thrown to exit a try/catch block for isolated transactions
Properties¶
Methods¶
Phalcon\Mvc\Model\Transaction\Failed constructor Returns validation record messages which stop the transaction Returns validation record messages which stop the transactionMvc\Model\Transaction\Manager¶
-
Namespace
Phalcon\Mvc\Model\Transaction
-
Uses
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\Model\Transaction
Phalcon\Mvc\Model\TransactionInterface
-
Extends
-
Implements
InjectionAwareInterface
ManagerInterface
Phalcon\Mvc\Model\Transaction\Manager
A transaction acts on a single database connection. If you have multiple class-specific databases, the transaction will not protect interaction among them.
This class manages the objects that compose a transaction. A transaction produces a unique connection that is passed to every object part of the transaction.
use Phalcon\Mvc\Model\Transaction\Failed;
use Phalcon\Mvc\Model\Transaction\Manager;
try {
$transactionManager = new Manager();
$transaction = $transactionManager->get();
$robot = new Robots();
$robot->setTransaction($transaction);
$robot->name = "WALL·E";
$robot->created_at = date("Y-m-d");
if ($robot->save() === false) {
$transaction->rollback("Can't save robot");
}
$robotPart = new RobotParts();
$robotPart->setTransaction($transaction);
$robotPart->type = "head";
if ($robotPart->save() === false) {
$transaction->rollback("Can't save robot part");
}
$transaction->commit();
} catch (Failed $e) {
echo "Failed, reason: ", $e->getMessage();
}
Properties¶
//
protected $container;
//
protected $initialized = false;
//
protected $number = 0;
//
protected $rollbackPendent = true;
//
protected $service = db;
/**
* @var array
*/
protected $transactions;
Methods¶
Phalcon\Mvc\Model\Transaction\Manager constructor Remove all the transactions from the manager Commits active transactions within the manager Returns a new \Phalcon\Mvc\Model\Transaction or an already created once This method registers a shutdown function to rollback active connections Returns the dependency injection container Returns the database service used to isolate the transaction Create/Returns a new transaction or an existing one Check if the transaction manager is registering a shutdown function to clean up pendent transactions Checks whether the manager has an active transaction Notifies the manager about a committed transaction Notifies the manager about a rollbacked transaction Rollbacks active transactions within the manager Collect will remove the transaction from the manager Rollbacks active transactions within the manager Sets the dependency injection container Sets the database service used to run the isolated transactions Set if the transaction manager must register a shutdown function to clean up pendent transactions Removes transactions from the TransactionManagerMvc\Model\Transaction\ManagerInterface ¶
-
Namespace
Phalcon\Mvc\Model\Transaction
-
Uses
Phalcon\Mvc\Model\TransactionInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\Transaction\ManagerInterface
Interface for Phalcon\Mvc\Model\Transaction\Manager
Methods¶
Remove all the transactions from the manager Commits active transactions within the manager Returns a new \Phalcon\Mvc\Model\Transaction or an already created once Returns the database service used to isolate the transaction Check if the transaction manager is registering a shutdown function to clean up pendent transactions Checks whether manager has an active transaction Notifies the manager about a committed transaction Notifies the manager about a rollbacked transaction Rollbacks active transactions within the manager Collect will remove transaction from the manager Rollbacks active transactions within the manager Sets the database service used to run the isolated transactions Set if the transaction manager must register a shutdown function to clean up pendent transactionsMvc\Model\TransactionInterface ¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Transaction\ManagerInterface
-
Extends
-
Implements
Phalcon\Mvc\Model\TransactionInterface
Interface for Phalcon\Mvc\Model\Transaction
Methods¶
Starts the transaction Commits the transaction Returns connection related to transaction Returns validations messages from last save try Checks whether transaction is managed by a transaction manager Checks whether internal connection is under an active transactionpublic function rollback( string $rollbackMessage = null, ModelInterface $rollbackRecord = null ): bool;
Mvc\Model\ValidationFailed¶
-
Namespace
Phalcon\Mvc\Model
-
Uses
Phalcon\Messages\Message
Phalcon\Mvc\ModelInterface
-
Extends
Exception
-
Implements
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
Properties¶
Methods¶
Phalcon\Mvc\Model\ValidationFailed constructor Returns the complete group of messages produced in the validation Returns the model that generated the messagesMvc\ModelInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Di\DiInterface
Phalcon\Messages\MessageInterface
Phalcon\Mvc\Model\CriteriaInterface
Phalcon\Mvc\Model\MetaDataInterface
Phalcon\Mvc\Model\ResultsetInterface
Phalcon\Mvc\Model\TransactionInterface
-
Extends
-
Implements
Phalcon\Mvc\ModelInterface
Interface for Phalcon\Mvc\Model
Methods¶
Appends a customized message on the validation processpublic function assign( array $data, mixed $whiteList = null, mixed $dataColumnMap = null ): ModelInterface;
public static function cloneResult( ModelInterface $base, array $data, int $dirtyState = int ): ModelInterface;
public static function cloneResultMap( mixed $base, array $data, mixed $columnMap, int $dirtyState = int, bool $keepSnapshots = null ): ModelInterface;
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.
Inserts a model instance. If the instance already exists in the persistence it will throw an exception. Returning true on success or false otherwise. Deletes a model instance. Returning true on success or false otherwise. Allows to query a set of records that match the specified conditions Allows to query the first record that match the specified conditions Fires an event, implicitly calls behaviors and listeners in the events manager are notified 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 Returns one of the DIRTY_STATE_* constants telling if the record exists in the database or not Returns array of validation messages Returns the models meta-data service related to the entity instance. Returns the type of the latest operation performed by the ORM Returns one of the OP_* class constants Gets internal database connection Returns DependencyInjection connection service used to read data Returns related records based on defined relations Returns schema name where table mapped is located Returns table name mapped in the model Gets internal database connection Returns DependencyInjection connection service used to write data Allows to get the maximum value of a column that match the specified conditions Allows to get the minimum value of a column that match the specified conditions Create a criteria for a specific model Refreshes the model attributes re-querying the record from the database Inserts or updates a model instance. Returning true on success or false otherwise. Sets both read/write connection services Sets the dirty state of the object using one of the DIRTY_STATE_* constants Sets the DependencyInjection connection service used to read data 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 Sets a transaction related to the Model instance Sets the DependencyInjection connection service used to write data Skips the current operation forcing a success state Allows to calculate a sum on a column that match the specified conditions Updates a model instance. If the instance doesn't exist in the persistence it will throw an exception. Returning true on success or false otherwise. Check whether validation process has generated any messagesMvc\ModuleDefinitionInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Di\DiInterface
-
Extends
-
Implements
Phalcon\Mvc\ModuleDefinitionInterface
This interface must be implemented by class module definitions
Methods¶
Registers an autoloader related to the module Registers services related to the moduleMvc\Router¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Di\AbstractInjectionAware
Phalcon\Di\DiInterface
Phalcon\Events\EventsAwareInterface
Phalcon\Events\ManagerInterface
Phalcon\Http\RequestInterface
Phalcon\Mvc\Router\Exception
Phalcon\Mvc\Router\GroupInterface
Phalcon\Mvc\Router\Route
Phalcon\Mvc\Router\RouteInterface
-
Extends
AbstractInjectionAware
-
Implements
EventsAwareInterface
RouterInterface
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();
Constants¶
Properties¶
//
protected $action;
//
protected $controller;
//
protected $defaultAction;
//
protected $defaultController;
//
protected $defaultModule;
//
protected $defaultNamespace;
//
protected $defaultParams;
//
protected $eventsManager;
//
protected $keyRouteNames;
//
protected $keyRouteIds;
//
protected $matchedRoute;
//
protected $matches;
//
protected $module;
//
protected $namespaceName;
//
protected $notFoundPaths;
//
protected $params;
//
protected $removeExtraSlashes;
//
protected $routes;
//
protected $wasMatched = false;
Methods¶
Phalcon\Mvc\Router constructorpublic function add( string $pattern, mixed $paths = null, mixed $httpMethods = null, mixed $position = static-constant-access ): RouteInterface;
use Phalcon\Mvc\Router;
$router->add("/about", "About::index");
$router->add(
"/about",
"About::index",
["GET", "POST"]
);
$router->add(
"/about",
"About::index",
["GET", "POST"],
Router::POSITION_FIRST
);
public function addConnect( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addDelete( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addGet( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addHead( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addOptions( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addPatch( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addPost( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addPurge( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addPut( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function addTrace( string $pattern, mixed $paths = null, mixed $position = static-constant-access ): RouteInterface;
public function attach( RouteInterface $route, mixed $position = static-constant-access ): RouterInterface;
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
);
Mvc\Router\Annotations¶
-
Namespace
Phalcon\Mvc\Router
-
Uses
Phalcon\Annotations\Annotation
Phalcon\Di\DiInterface
Phalcon\Mvc\Router
-
Extends
Router
-
Implements
Phalcon\Mvc\Router\Annotations
A router that reads routes annotations from classes/resources
use Phalcon\Mvc\Router\Annotations;
$di->setShared(
"router",
function() {
// Use the annotations router
$router = new Annotations(false);
// This will do the same as above but only if the handled uri starts with /robots
$router->addResource("Robots", "/robots");
return $router;
}
);
Properties¶
//
protected $actionSuffix = Action;
//
protected $actionPreformatCallback;
//
protected $controllerSuffix = Controller;
//
protected $handlers;
//
protected $routePrefix;
Methods¶
public function addModuleResource( string $module, string $handler, string $prefix = null ): Annotations;
public function processActionAnnotation( string $module, string $namespaceName, string $controller, string $action, Annotation $annotation );
// Array as callback
$annotationRouter->setActionPreformatCallback([Text::class, 'uncamelize']);
// 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();
Mvc\Router\Exception¶
-
Namespace
Phalcon\Mvc\Router
-
Uses
-
Extends
\Exception
-
Implements
Phalcon\Mvc\Router\Exception
Exceptions thrown in Phalcon\Mvc\Router will use this class
Mvc\Router\Group¶
-
Namespace
Phalcon\Mvc\Router
-
Uses
-
Extends
-
Implements
GroupInterface
Phalcon\Mvc\Router\Group
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);
Properties¶
//
protected $beforeMatch;
//
protected $hostname;
//
protected $paths;
//
protected $prefix;
//
protected $routes;
Methods¶
Phalcon\Mvc\Router\Group constructorpublic function add( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
protected function addRoute( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
Mvc\Router\GroupInterface ¶
-
Namespace
Phalcon\Mvc\Router
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\Router\GroupInterface
$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);
Methods¶
public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
Mvc\Router\Route¶
-
Namespace
Phalcon\Mvc\Router
-
Uses
-
Extends
-
Implements
RouteInterface
Phalcon\Mvc\Router\Route
This class represents every route added to the router
Properties¶
//
protected $beforeMatch;
//
protected $compiledPattern;
//
protected $converters;
//
protected $group;
//
protected $hostname;
//
protected $id;
//
protected $methods;
//
protected $match;
//
protected $name;
//
protected $paths;
//
protected $pattern;
//
protected $static uniqueId = 0;
Methods¶
Phalcon\Mvc\Router\Route constructor 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;
}
);
$router->add(
"/help",
[]
)->match(
function () {
return $this->getResponse()->redirect("https://support.google.com/", true);
}
);
Mvc\Router\RouteInterface ¶
-
Namespace
Phalcon\Mvc\Router
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\Router\RouteInterface
Interface for Phalcon\Mvc\Router\Route
Methods¶
Replaces placeholders from pattern returning a valid PCRE regular expression Adds a converter to perform an additional transformation for certain parameter. Returns the route's pattern Returns the hostname restriction if any Returns the HTTP methods that constraint matching the route Returns the route's name Returns the paths Returns the route's pattern Returns the paths using positions as keys and names as values Returns the route's id Reconfigure the route adding a new pattern and a set of paths Resets the internal route id generator Sets a hostname restriction to the route Sets a set of HTTP methods that constraint the matching of the route Sets the route's name Set one or more HTTP methods that constraint the matching of the routeMvc\RouterInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Mvc\Router\GroupInterface
Phalcon\Mvc\Router\RouteInterface
-
Extends
-
Implements
Interface for Phalcon\Mvc\Router
Methods¶
public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
public function attach( RouteInterface $route, mixed $position = static-constant-access ): RouterInterface;
Mvc\View¶
-
Namespace
Phalcon\Mvc
-
Uses
Closure
Phalcon\Di\DiInterface
Phalcon\Di\Injectable
Phalcon\Events\EventsAwareInterface
Phalcon\Events\ManagerInterface
Phalcon\Mvc\View\Engine\Php
Phalcon\Mvc\View\Exception
-
Extends
Injectable
-
Implements
EventsAwareInterface
ViewInterface
Phalcon\Mvc\View
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();
Constants¶
const LEVEL_ACTION_VIEW = 1;
const LEVEL_AFTER_TEMPLATE = 4;
const LEVEL_BEFORE_TEMPLATE = 2;
const LEVEL_LAYOUT = 3;
const LEVEL_MAIN_LAYOUT = 5;
const LEVEL_NO_RENDER = 0;
Properties¶
//
protected $actionName;
//
protected $activeRenderPaths;
//
protected $basePath = ;
//
protected $content = ;
//
protected $controllerName;
//
protected $currentRenderLevel = 0;
//
protected $disabled = false;
//
protected $disabledLevels;
//
protected $engines = false;
//
protected $eventsManager;
//
protected $layout;
//
protected $layoutsDir = ;
//
protected $mainView = index;
//
protected $options;
//
protected $params;
//
protected $pickView;
//
protected $partialsDir = ;
//
protected $registeredEngines;
//
protected $renderLevel = 5;
//
protected $templatesAfter;
//
protected $templatesBefore;
//
protected $viewsDirs;
//
protected $viewParams;
Methods¶
Phalcon\Mvc\View constructor Magic method to retrieve a variable passed to the view Magic method to retrieve if a variable is set in the view Magic method to pass variables to the views Resets any template before layouts Resets any "template before" layouts Disables the auto-rendering process Disables a specific level of rendering Enables the auto-rendering process Checks whether view exists Finishes the render process by stopping the output buffering Gets the name of the action rendered Returns the path (or paths) of the views that are currently rendered Gets base path Returns output from another view stage Gets the name of the controller rendered Returns the internal event manager Returns the name of the main view Gets the current layouts sub-directory Returns the name of the main view Returns parameters to views Renders a partial view// Retrieve the contents of a partial with arguments
echo $this->getPartial(
"shared/footer",
[
"content" => $html,
]
);
public function getRender( string $controllerName, string $actionName, array $params = [], mixed $configCallback = null ): string;
// Show a partial inside another view with parameters
$this->partial(
"shared/footer",
[
"content" => $html,
]
);
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");
}
}
public function processRender( string $controllerName, string $actionName, array $params = [], bool $fireEvents = bool ): bool;
$this->view->registerEngines(
[
".phtml" => \Phalcon\Mvc\View\Engine\Php::class,
".volt" => \Phalcon\Mvc\View\Engine\Volt::class,
".mhtml" => \MyCustomEngine::class,
]
);
public function render( string $controllerName, string $actionName, array $params = [] ): View | bool;
// Shows recent posts view (app/views/posts/recent.phtml)
$view->start()->render("posts", "recent")->finish();
// Render the view related to the controller only
$this->view->setRenderLevel(
View::LEVEL_LAYOUT
);
protected function engineRender( array $engines, string $viewPath, bool $silence, bool $mustClean = bool );
Mvc\View\Engine\AbstractEngine ¶
-
Namespace
Phalcon\Mvc\View\Engine
-
Uses
Phalcon\Di\DiInterface
Phalcon\Di\Injectable
Phalcon\Mvc\ViewBaseInterface
-
Extends
Injectable
-
Implements
EngineInterface
All the template engine adapters must inherit this class. This provides basic interfacing between the engine and the Phalcon\Mvc\View component.
Properties¶
Methods¶
Phalcon\Mvc\View\Engine constructor Returns cached output on another view stage Returns the view component related to the adapter Renders a partial inside another viewMvc\View\Engine\EngineInterface ¶
-
Namespace
Phalcon\Mvc\View\Engine
-
Uses
-
Extends
-
Implements
Interface for Phalcon\Mvc\View engine adapters
Methods¶
Returns cached output on another view stage Renders a partial inside another view Renders a view using the template engineMvc\View\Engine\Php¶
-
Namespace
Phalcon\Mvc\View\Engine
-
Uses
-
Extends
AbstractEngine
-
Implements
Adapter to use PHP itself as templating engine
Methods¶
Renders a view using the template engineMvc\View\Engine\Volt¶
-
Namespace
Phalcon\Mvc\View\Engine
-
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\Exception
-
Extends
AbstractEngine
-
Implements
EventsAwareInterface
Designer friendly and fast template engine for PHP written in Zephir/C
Properties¶
Methods¶
Checks if a macro is defined and calls it Performs a string conversion Returns the Volt's compiler Returns the internal event manager Return Volt's options Checks if the needle is included in the haystack Length filter. If an array/object is passed a count is performed otherwise a strlen/mb_strlen Renders a view using the template engine Sets the events manager Set Volt's options Extracts a slice from a string/array/traversable object value Sorts an arrayMvc\View\Engine\Volt\Compiler¶
-
Namespace
Phalcon\Mvc\View\Engine\Volt
-
Uses
Closure
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\ViewBaseInterface
-
Extends
-
Implements
InjectionAwareInterface
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();
Properties¶
//
protected $autoescape = false;
//
protected $blockLevel = 0;
//
protected $blocks;
//
protected $container;
//
protected $compiledTemplatePath;
//
protected $currentBlock;
//
protected $currentPath;
//
protected $exprLevel = 0;
//
protected $extended = false;
//
protected $extensions;
//
protected $extendedBlocks;
//
protected $filters;
//
protected $foreachLevel = 0;
//
protected $forElsePointers;
//
protected functions;
//
protected $level = 0;
//
protected $loopPointers;
//
protected $macros;
//
protected $options;
//
protected $prefix;
//
protected $view;
Methods¶
Phalcon\Mvc\View\Engine\Volt\Compiler Registers a Volt's extension Register a new filter in the compiler Register a new function in the compiler Resolves attribute reading Compiles a template into a file applying the compiler options This method does not return the compiled path if the template was not compiled Compiles a "autoescape" statement returning PHP code Compiles a "cache" statement returning PHP code@deprecated Will be removed in 5.0 @todo Remove this in the next major version
Compiles calls to macros Compiles a "case"/"default" clause returning PHP code Compiles a "do" statement returning PHP code Compiles a {% raw %}{{
}}
statement returning PHP code Compiles a "elseif" statement returning PHP code Compiles a template into a file forcing the destination path Generates a 'forelse' PHP code Compiles a "foreach" intermediate code representation into plain PHP code Compiles a 'if' statement returning PHP code Compiles a 'include' statement returning PHP code Compiles macros Compiles a "return" statement returning PHP code Compiles a "set" statement returning PHP code Compiles a template into a string Compiles a 'switch' statement returning PHP code Resolves an expression node in an AST volt tree Fires an event to registered extensions Resolves function intermediate code into PHP function calls Returns the path to the last compiled template Returns the internal dependency injector Returns the list of extensions registered in Volt Register the user registered filters Register the user registered functions Returns a compiler's option Returns the compiler options Returns the path that is currently being compiled Return a unique prefix to be used as prefix for compiled variables and contexts Parses a Volt template returning its intermediate representation Resolves filter intermediate code into a valid PHP expression Sets the dependency injector Sets a single compiler option Sets the compiler options Set a unique prefix to be used as prefix for compiled variables Compiles a Volt source code returning a PHP plain version Gets the final path with VIEW Resolves filter intermediate code into PHP function calls Traverses a statement list compiling each of its nodes Compiles a block of statements Mvc\View\Engine\Volt\Exception¶
-
Namespace
Phalcon\Mvc\View\Engine\Volt
-
Uses
Phalcon\Mvc\View\Exception
-
Extends
BaseException
-
Implements
Class for exceptions thrown by Phalcon\Mvc\View
Properties¶
Methods¶
public function __construct( string $message = string, array $statement = [], int $code = int, \Exception $previous = null );
Mvc\View\Exception¶
-
Namespace
Phalcon\Mvc\View
-
Uses
-
Extends
\Exception
-
Implements
Phalcon\Mvc\View\Exception
Class for exceptions thrown by Phalcon\Mvc\View
Mvc\View\Simple¶
-
Namespace
Phalcon\Mvc\View
-
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
-
Extends
Injectable
-
Implements
EventsAwareInterface
ViewBaseInterface
Phalcon\Mvc\View\Simple
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,
]
);
Properties¶
//
protected $activeRenderPath;
//
protected $content;
/**
* @var \Phalcon\Mvc\View\EngineInterface[]|false
*/
protected $engines = false;
//
protected $eventsManager;
//
protected $options;
//
protected $partialsDir;
/**
* @var array|null
*/
protected $registeredEngines;
//
protected $viewsDir;
//
protected $viewParams;
Methods¶
Phalcon\Mvc\View\Simple constructor Magic method to retrieve a variable passed to the view Magic method to pass variables to the views Returns the path of the view that is currently rendered Returns output from another view stage Returns the internal event manager Returns parameters to views Returns a parameter previously set in the view Gets views directory Renders a partial view// Show a partial inside another view with parameters
$this->partial(
"shared/footer",
[
"content" => $html,
]
);
$this->view->registerEngines(
[
".phtml" => \Phalcon\Mvc\View\Engine\Php::class,
".volt" => \Phalcon\Mvc\View\Engine\Volt::class,
".mhtml" => \MyCustomEngine::class,
]
);
Mvc\ViewBaseInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Cache\Adapter\AdapterInterface
-
Extends
-
Implements
Phalcon\Mvc\ViewInterface
Interface for Phalcon\Mvc\View and Phalcon\Mvc\View\Simple
Methods¶
Returns cached output from another view stage Returns parameters to views Gets views directory Renders a partial view Externally sets the view content Adds parameters to views (alias of setVar) Adds parameters to views Sets views directory. Depending of your platform, always add a trailing slash or backslashMvc\ViewInterface ¶
-
Namespace
Phalcon\Mvc
-
Uses
-
Extends
ViewBaseInterface
-
Implements
Phalcon\Mvc\ViewInterface
Interface for Phalcon\Mvc\View