Phalcon mvc
NOTE
All classes are prefixed with Phalcon
Mvc\Application¶
-
Namespace
Phalcon\Mvc
-
Uses
ClosurePhalcon\Application\AbstractApplicationPhalcon\Di\DiInterfacePhalcon\Events\ManagerInterfacePhalcon\Http\ResponseInterfacePhalcon\Mvc\Application\ExceptionPhalcon\Mvc\ModuleDefinitionInterfacePhalcon\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¶
/**
* @var bool
*/
protected $implicitView = true;
/**
* @var bool
*/
protected $sendCookies = true;
/**
* @var bool
*/
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
$this->dispatcher->forward(
[
"controller" => "people",
"action" => "index",
]
);
}
}
Methods¶
Phalcon\Mvc\Controller constructorMvc\Controller\BindModelInterface
¶
-
Namespace
Phalcon\Mvc\Controller
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\Controller\BindModelInterface
Interface for Phalcon\Mvc\Controller
Methods¶
Return the model name associated with this controllerMvc\ControllerInterface
¶
-
Namespace
Phalcon\Mvc
-
Uses
-
Extends
-
Implements
Phalcon\Mvc\ControllerInterface
Interface for controller handlers
Mvc\Dispatcher¶
-
Namespace
Phalcon\Mvc
-
Uses
Phalcon\Dispatcher\AbstractDispatcherPhalcon\Events\ManagerInterfacePhalcon\Http\ResponseInterfacePhalcon\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\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
Phalcon\Mvc\DispatcherInterface
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
ArrayAccessClosurePhalcon\Di\DiInterfacePhalcon\Di\FactoryDefaultPhalcon\Di\InjectablePhalcon\Di\ServiceInterfacePhalcon\Events\EventsAwareInterfacePhalcon\Events\ManagerInterfacePhalcon\Http\ResponseInterfacePhalcon\Mvc\Micro\CollectionPhalcon\Mvc\Micro\CollectionInterfacePhalcon\Mvc\Micro\ExceptionPhalcon\Mvc\Micro\LazyLoaderPhalcon\Mvc\Micro\MiddlewareInterfacePhalcon\Mvc\Model\BinderInterfacePhalcon\Mvc\Router\RouteInterfaceThrowable
-
Extends
Injectable -
Implements
ArrayAccessEventsAwareInterface
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¶
/**
* @var callable|null
*/
protected $activeHandler;
/**
* @var array
*/
protected $afterBindingHandlers;
/**
* @var array
*/
protected $afterHandlers;
/**
* @var array
*/
protected $beforeHandlers;
/**
* @var DiInterface|null
*/
protected $container;
/**
* @var callable|null
*/
protected $errorHandler;
/**
* @var ManagerInterface|null
*/
protected $eventsManager;
/**
* @var array
*/
protected $finishHandlers;
/**
* @var array
*/
protected $handlers;
/**
* @var BinderInterface|null
*/
protected $modelBinder;
/**
* @var callable|null
*/
protected $notFoundHandler;
/**
* @var callable|null
*/
protected $responseHandler;
/**
* @var mixed|null
*/
protected $returnedValue;
/**
* @var RouterInterface|null
*/
protected $router;
/**
* @var bool
*/
protected $stopped = false;
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¶
/**
* @var callable
*/
protected $handler;
/**
* @var array
*/
protected $handlers;
/**
* @var bool
*/
protected $lazy = false;
/**
* @var string
*/
protected $prefix = ;
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 mapVia( string $routePattern, callable $handler, mixed $method, 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;
protected function addMap( mixed $method, string $routePattern, callable $handler, string $name = null ): void;
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
\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
JsonSerializablePhalcon\Db\Adapter\AdapterInterfacePhalcon\Db\ColumnPhalcon\Db\DialectInterfacePhalcon\Db\EnumPhalcon\Db\RawValuePhalcon\Di\AbstractInjectionAwarePhalcon\Di\DiPhalcon\Di\DiInterfacePhalcon\Events\ManagerInterfacePhalcon\Filter\Validation\ValidationInterfacePhalcon\Messages\MessagePhalcon\Messages\MessageInterfacePhalcon\Mvc\ModelInterfacePhalcon\Mvc\Model\BehaviorInterfacePhalcon\Mvc\Model\CriteriaPhalcon\Mvc\Model\CriteriaInterfacePhalcon\Mvc\Model\ExceptionPhalcon\Mvc\Model\ManagerInterfacePhalcon\Mvc\Model\MetaDataInterfacePhalcon\Mvc\Model\QueryPhalcon\Mvc\Model\QueryInterfacePhalcon\Mvc\Model\Query\BuilderPhalcon\Mvc\Model\Query\BuilderInterfacePhalcon\Mvc\Model\RelationPhalcon\Mvc\Model\RelationInterfacePhalcon\Mvc\Model\ResultInterfacePhalcon\Mvc\Model\ResultsetPhalcon\Mvc\Model\ResultsetInterfacePhalcon\Mvc\Model\TransactionInterfacePhalcon\Mvc\Model\ValidationFailedPhalcon\Support\CollectionPhalcon\Support\Collection\CollectionInterfaceSerializable
-
Extends
AbstractInjectionAware -
Implements
EntityInterfaceJsonSerializableModelInterfaceResultInterfaceSerializable
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¶
/**
* @var int
*/
protected $dirtyState = 1;
/**
* @var array
*/
protected $dirtyRelated;
/**
* @var array
*/
protected $errorMessages;
/**
* @var ManagerInterface|null
*/
protected $modelsManager;
/**
* @var MetaDataInterface|null
*/
protected $modelsMetaData;
/**
* @var array
*/
protected $related;
/**
* @var int
*/
protected $operationMade = ;
/**
* @var array
*/
protected $oldSnapshot;
/**
* @var bool
*/
protected $skipped = false;
/**
* @var array
*/
protected $snapshot;
/**
* @var TransactionInterface|null
*/
protected $transaction;
/**
* @var string|null
*/
protected $uniqueKey;
/**
* @var array
*/
protected $uniqueParams;
/**
* @var array
*/
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\Di::getDefault());
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newRobot->save();
$resultInsideTransaction = Robot::find(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$resultOutsideTransaction = Robot::find(['name' => 'test']);
foreach ($setInsideTransaction as $robot) {
echo $robot->name, "\n";
}
foreach ($setOutsideTransaction as $robot) {
echo $robot->name, "\n";
}
// reverts all not commited changes
$myTransaction->rollback();
// creating two different transactions
$myTransaction1 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction1->begin();
$myTransaction2 = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction2->begin();
// add a new robots
$firstNewRobot = new Robot();
$firstNewRobot->setTransaction($myTransaction1);
$firstNewRobot->assign(
[
'name' => 'first-transaction-robot',
'type' => 'mechanical',
'year' => 1944,
]
);
$firstNewRobot->save();
$secondNewRobot = new Robot();
$secondNewRobot->setTransaction($myTransaction2);
$secondNewRobot->assign(
[
'name' => 'second-transaction-robot',
'type' => 'fictional',
'year' => 1984,
]
);
$secondNewRobot->save();
// this transaction will find the robot.
$resultInFirstTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the robot.
$resultInSecondTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
[
'name' => 'first-transaction-robot',
]
);
// this transaction won't find the robot.
$resultInFirstTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction2,
]
);
// this transaction will find the robot.
$resultInSecondTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
Model::TRANSACTION_INDEX => $myTransaction1,
]
);
// this transaction won't find the robot.
$resultOutsideAnyExplicitTransaction = Robot::find(
[
'name' => 'second-transaction-robot',
]
);
$transaction1->rollback();
$transaction2->rollback();
// What's the first robot in robots table?
$robot = Robots::findFirst();
echo "The robot name is ", $robot->name;
// What's the first mechanical robot in robots table?
$robot = Robots::findFirst(
"type = 'mechanical'"
);
echo "The first mechanical robot name is ", $robot->name;
// Get first virtual robot ordered by name
$robot = Robots::findFirst(
[
"type = 'virtual'",
"order" => "name",
]
);
echo "The first virtual robot name is ", $robot->name;
// behaviour with transaction
$myTransaction = new Transaction(\Phalcon\Di\Di::getDefault());
$myTransaction->begin();
$newRobot = new Robot();
$newRobot->setTransaction($myTransaction);
$newRobot->assign(
[
'name' => 'test',
'type' => 'mechanical',
'year' => 1944,
]
);
$newRobot->save();
$findsARobot = Robot::findFirst(
[
'name' => 'test',
Model::TRANSACTION_INDEX => $myTransaction,
]
);
$doesNotFindARobot = Robot::findFirst(
[
'name' => 'test',
]
);
var_dump($findARobot);
var_dump($doesNotFindARobot);
$transaction->commit();
$doesFindTheRobotNow = Robot::findFirst(
[
'name' => 'test',
]
);
$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";
false, getter methods for properties will be ignored. Unserializes the object from a serialized string 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. <?php
use MyApp\Models\Invoices;
$invoice = Invoices::findFirst('inv_id = 4');
$invoice->inv_total = 120;
$invoice->update();
NOTE
When retrieving the record with findFirst(), you need to get the full object back (no columns definition) but also retrieve it using the primary key. If not, the ORM will issue an INSERT instead of UPDATE.
use Phalcon\Mvc\Model;
use Phalcon\Filter\Validation;
use Phalcon\Filter\Validation\Validator\ExclusionIn;
class Subscriptors extends Model
{
public function validation()
{
$validator = new Validation();
$validator->validate(
"status",
new ExclusionIn(
[
"domain" => [
"A",
"I",
],
]
)
);
return $this->validate($validator);
}
}
class Robots extends \Phalcon\Mvc\Model
{
public function initialize()
{
$this->allowEmptyStringValues(
[
"name",
]
);
}
}
protected function belongsTo( mixed $fields, string $referenceModel, mixed $referencedFields, array $options = [] ): 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 = null ): ResultsetInterface;
protected function hasMany( mixed $fields, string $referenceModel, mixed $referencedFields, array $options = [] ): 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, array $options = [] ): 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, array $options = [] ): 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, array $options = [] ): 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 postSaveRelatedRecords( AdapterInterface $connection, mixed $related, CollectionInterface $visited ): bool;
protected function preSave( MetaDataInterface $metaData, bool $exists, mixed $identityField ): bool;
protected function preSaveRelatedRecords( AdapterInterface $connection, mixed $related, CollectionInterface $visited ): 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\Filter\Validation;
use Phalcon\Filter\Validation\Validator\ExclusionIn;
class Subscriptors extends Model
{
public function validation()
{
$validator = new Validation();
$validator->add(
"status",
new ExclusionIn(
[
"domain" => [
"A",
"I",
],
]
)
);
return $this->validate($validator);
}
}
Mvc\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\ModelInterfacePhalcon\Mvc\Model\BehaviorPhalcon\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
ClosurePhalcon\Mvc\ModelInterfacePhalcon\Mvc\Model\BehaviorPhalcon\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
ClosurePhalcon\Cache\Adapter\AdapterInterfacePhalcon\Mvc\Controller\BindModelInterfacePhalcon\Mvc\Model\Binder\BindableInterfaceReflectionFunctionReflectionMethod
-
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
*
* @var AdapterInterface|null
*/
protected $cache;
/**
* Internal cache for caching parameters for model binding during request
*
* @var array
*/
protected $internalCache;
/**
* Array for original values
*
* @var array
*/
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\ColumnPhalcon\Di\DiPhalcon\Di\DiInterfacePhalcon\Di\InjectionAwareInterfacePhalcon\Mvc\Model\Query\BuilderInterface
-
Extends
-
Implements
CriteriaInterfaceInjectionAwareInterface
This class is used to build the array parameter required by Phalcon\Mvc\Model::find() and Phalcon\Mvc\Model::findFirst() using an object-oriented interface.
<?php
$invoices = Invoices::query()
->where("inv_cst_id = :customerId:")
->andWhere("inv_created_date < '2000-01-01'")
->bind(["customerId" => 1])
->limit(5, 10)
->orderBy("inv_title")
->execute();
Properties¶
/**
* @var array
*/
protected $bindParams;
/**
* @var array
*/
protected $bindTypes;
/**
* @var int
*/
protected $hiddenParamNumber = ;
/**
* @var string|null
*/
protected $model;
/**
* @var array
*/
protected $params;
Methods¶
public function andWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
string or an array of strings. If the argument is a (single, non-embedded) string, its content can specify one or more columns, separated by commas, the same way that one uses the SQL select statement. You can use aliases, aggregate functions, etc. If you need to reference other models you will need to reference them with their namespaces. When using an array as a parameter, you will need to specify one field per array element. If a non-numeric key is defined in the array, it will be used as the alias in the query
<?php
// String, comma separated values
$criteria->columns("id, category");
// Array, one column per element
$criteria->columns(
[
"inv_id",
"inv_total",
]
);
// Array with named key. The name of the key acts as an
// alias (`AS` clause)
$criteria->columns(
[
"inv_cst_id",
"total_invoices" => "COUNT(*)",
]
);
// Different models
$criteria->columns(
[
"\Phalcon\Models\Invoices.*",
"\Phalcon\Models\Customers.cst_name_first",
"\Phalcon\Models\Customers.cst_name_last",
]
);
public static function fromInput( DiInterface $container, string $modelName, array $data, string $operator = string ): CriteriaInterface;
public function innerJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
<?php
$criteria->innerJoin(
Invoices::class
);
$criteria->innerJoin(
Invoices::class,
"inv_cst_id = Customers.cst_id"
);
$criteria->innerJoin(
Invoices::class,
"i.inv_cst_id = Customers.cst_id",
"i"
);
public function join( string $model, mixed $conditions = null, mixed $alias = null, mixed $type = null ): CriteriaInterface;
<?php
$criteria->join(
Invoices::class
);
$criteria->join(
Invoices::class,
"inv_cst_id = Customers.cst_id"
);
$criteria->join(
Invoices::class,
"i.inv_cst_id = Customers.cst_id",
"i"
);
$criteria->join(
Invoices::class,
"i.inv_cst_id = Customers.cst_id",
"i",
"LEFT"
);
public function leftJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function orWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
public function rightJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function where( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
public function andWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
public function innerJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
$criteria->innerJoin(
Robots::class
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id"
);
$criteria->innerJoin(
Robots::class,
"r.id = RobotsParts.robots_id",
"r"
);
public function leftJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function orWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
public function rightJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
public function where( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
use Phalcon\Di\Di;
use Phalcon\Mvc\Model\Manager as ModelsManager;
$di = new Di();
$di->set(
"modelsManager",
function() {
return new ModelsManager();
}
);
$robot = new Robots($di);
/**
* @var array
*/
protected $aliases;
/**
* Models' behaviors
*
* @var array
*/
protected $behaviors;
/**
* Belongs to relations
*
* @var array
*/
protected $belongsTo;
/**
* All the relationships by model
*
* @var array
*/
protected $belongsToSingle;
/**
* @var BuilderInterface|null
*/
protected $builder;
/**
* @var DiInterface|null
*/
protected $container;
/**
* @var array
*/
protected $customEventsManager;
/**
* Does the model use dynamic update, instead of updating all rows?
*
* @var array
*/
protected $dynamicUpdate;
/**
* @var EventsManagerInterface|null
*/
protected $eventsManager;
/**
* Has many relations
*
* @var array
*/
protected $hasMany;
/**
* Has many relations by model
*
* @var array
*/
protected $hasManySingle;
/**
* Has many-Through relations
*
* @var array
*/
protected $hasManyToMany;
/**
* Has many-Through relations by model
*
* @var array
*/
protected $hasManyToManySingle;
/**
* Has one relations
*
* @var array
*/
protected $hasOne;
/**
* Has one relations by model
*
* @var array
*/
protected $hasOneSingle;
/**
* Has one through relations
*
* @var array
*/
protected $hasOneThrough;
/**
* Has one through relations by model
*
* @var array
*/
protected $hasOneThroughSingle;
/**
* Mark initialized models
*
* @var array
*/
protected $initialized;
/**
* @var array
*/
protected $keepSnapshots;
/**
* Last model initialized
*
* @var ModelInterface|null
*/
protected $lastInitialized;
/**
* Last query created/executed
*
* @var QueryInterface|null
*/
protected $lastQuery;
/**
* @var array
*/
protected $modelVisibility;
/**
* @var string
*/
protected $prefix = ;
/**
* @var array
*/
protected $readConnectionServices;
/**
* @var array
*/
protected $sources;
/**
* @var array
*/
protected $schemas;
/**
* @var array
*/
protected $writeConnectionServices;
/**
* Stores a list of reusable instances
*
* @var array
*/
protected $reusable;
public function addBelongsTo( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasMany( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasManyToMany( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasOne( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasOneThrough( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function executeQuery( string $phql, mixed $placeholders = null, mixed $types = null ): mixed;
$model = new Robots();
$manager = $model->getModelsManager();
// \Phalcon\Mvc\Model\Resultset\Simple
$manager->executeQuery('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, array $connectionServices ): AdapterInterface;
public function addBelongsTo( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasMany( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasManyToMany( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasOne( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function addHasOneThrough( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
public function executeQuery( string $phql, mixed $placeholders = null, mixed $types = null ): mixed;
public function getBelongsToRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
public function getHasManyRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
public function getHasOneRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ModelInterface | bool;
public function getRelationRecords( RelationInterface $relation, ModelInterface $record, mixed $parameters = null, string $method = null );
$metaData = new \Phalcon\Mvc\Model\MetaData\Memory();
$attributes = $metaData->getAttributes(
new Robots()
);
print_r($attributes);
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;
/**
* @var CacheAdapterInterface|null
*/
protected $adapter;
/**
* @var array
*/
protected $columnMap;
/**
* @var DiInterface|null
*/
protected $container;
/**
* @var array
*/
protected $metaData;
/**
* @var StrategyInterface|null
*/
protected $strategy;
print_r(
$metaData->writeColumnMapIndex(
new Robots(),
MetaData::MODELS_REVERSE_COLUMN_MAP,
[
"leName" => "name",
]
)
);
final protected function initialize( ModelInterface $model, mixed $key, mixed $table, mixed $schema );
$metaData = new \Phalcon\Mvc\Model\MetaData\Apcu(
[
"prefix" => "my-app-id",
"lifetime" => 86400,
]
);
use Phalcon\Mvc\Model\MetaData\Redis;
$metaData = new Redis(
[
"host" => "127.0.0.1",
"port" => 6379,
"persistent" => 0,
"lifetime" => 172800,
"index" => 2,
]
);
$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();
/**
* @var array
* TODO: Add default value, instead of null, also remove type check
*/
protected $ast;
/**
* @var array
*/
protected $bindParams;
/**
* @var array
*/
protected $bindTypes;
/**
* @var mixed|null
*/
protected $cache;
/**
* @var array|null
*/
protected $cacheOptions;
/**
* @var DiInterface|null
*/
protected $container;
/**
* @var bool
*/
protected $enableImplicitJoins;
/**
* @var array
*/
protected $intermediate;
/**
* @var \Phalcon\Mvc\Model\ManagerInterface|null
*/
protected $manager;
/**
* @var \Phalcon\Mvc\Model\MetaDataInterface|null
*/
protected $metaData;
/**
* @var array
*/
protected $models;
/**
* @var array
*/
protected $modelsInstances;
/**
* @var int
*/
protected $nestingLevel = -1;
/**
* @var string|null
*/
protected $phql;
/**
* @var bool
*/
protected $sharedLock = false;
/**
* @var array
*/
protected $sqlAliases;
/**
* @var array
*/
protected $sqlAliasesModels;
/**
* @var array
*/
protected $sqlAliasesModelsInstances;
/**
* @var array
*/
protected $sqlColumnAliases;
/**
* @var array
*/
protected $sqlModelsAliases;
/**
* @var int|null
*/
protected $type;
/**
* @var bool
*/
protected $uniqueRow = false;
/**
* 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
*
* @var TransactionInterface|null
*/
protected $transaction;
/**
* @var array|null
*/
protected static $internalPhqlCache;
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;
protected function getReadConnection( ModelInterface $model, array $intermediate = null, array $bindParams = [], array $bindTypes = [] ): AdapterInterface;
final protected function getRelatedRecords( ModelInterface $model, array $intermediate, array $bindParams, array $bindTypes ): ResultsetInterface;
final protected function getSingleJoin( string $joinType, mixed $joinSource, string $modelAlias, string $joinAlias, RelationInterface $relation ): array;
protected function getWriteConnection( ModelInterface $model, array $intermediate = null, array $bindParams = [], array $bindTypes = [] ): AdapterInterface;
$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);
/**
* @var array
*/
protected $bindParams;
/**
* @var array
*/
protected $bindTypes;
/**
* @var array|string|null
*/
protected $columns;
/**
* @var array|string|null
*/
protected $conditions;
/**
* @var DiInterface|null
*/
protected $container;
/**
* @var mixed
*/
protected $distinct;
/**
* @var bool
*/
protected $forUpdate = false;
/**
* @var array
*/
protected $group;
/**
* @var string|null
*/
protected $having;
/**
* @var int
*/
protected $hiddenParamNumber = ;
/**
* @var array
*/
protected $joins;
/**
* @var array|string
*/
protected $limit;
/**
* @var array|string
*/
protected $models;
/**
* @var int
*/
protected $offset = ;
/**
* @var array|string
*/
protected $order;
/**
* @var bool
*/
protected $sharedLock = false;
// Load data from models Robots
$builder->addFrom(
Robots::class
);
// Load data from model 'Robots' using 'r' as alias in PHQL
$builder->addFrom(
Robots::class,
"r"
);
public function andHaving( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->andHaving("SUM(Robots.price) > 0");
$builder->andHaving(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function andWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->andWhere("name = 'Peter'");
$builder->andWhere(
"name = :name: AND id > :id:",
[
"name" => "Peter",
"id" => 100,
]
);
public function betweenHaving( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
public function betweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
<?php
// String, comma separated values
$builder->columns("id, category");
// Array, one column per element
$builder->columns(
[
"inv_id",
"inv_total",
]
);
// Array with named key. The name of the key acts as an
// alias (`AS` clause)
$builder->columns(
[
"inv_cst_id",
"total_invoices" => "COUNT(*)",
]
);
// Different models
$builder->columns(
[
"\Phalcon\Models\Invoices.*",
"\Phalcon\Models\Customers.cst_name_first",
"\Phalcon\Models\Customers.cst_name_last",
]
);
$builder->from(
Robots::class
);
$builder->from(
[
Robots::class,
RobotsParts::class,
]
);
$builder->from(
[
"r" => Robots::class,
"rp" => RobotsParts::class,
]
);
public function having( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
$builder->having("SUM(Robots.price) > 0");
$builder->having(
"SUM(Robots.price) > :sum:",
[
"sum" => 100,
]
);
public function inHaving( string $expr, array $values, string $operator = 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;
public function andWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
public function betweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
<?php
// String, comma separated values
$builder->columns("id, name");
// Array, one column per element
$builder->columns(
[
"id",
"name",
]
);
// Array, named keys. The name of the key acts as an alias (`AS` clause)
$builder->columns(
[
"name",
"number" => "COUNT(*)",
]
);
// Different models
$builder->columns(
[
"\Phalcon\Models\Invoices.*",
"\Phalcon\Models\Customers.cst_name_first",
"\Phalcon\Models\Customers.cst_name_last",
]
);
public function having( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
public function inWhere( string $expr, array $values, string $operator = 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;
use Phalcon\Mvc\Model\Query\Lang;
$intermediate = Lang::parsePHQL(
"SELECT r.* FROM Robots r LIMIT 10"
);
$phql = "UPDATE Robots SET name = :name:, type = :type:, year = :year: WHERE id = :id:";
$status = $app->modelsManager->executeQuery(
$phql,
[
"id" => 100,
"name" => "Astroy Boy",
"type" => "mechanical",
"year" => 1959,
]
);
// Check if the update was successful
if ($status->success()) {
echo "OK";
}
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;
/**
* @var array|string
*/
protected $fields;
/**
* @var array|string
*/
protected $intermediateFields;
/**
* @var string|null
*/
protected $intermediateModel;
/**
* @var array|string
*/
protected $intermediateReferencedFields;
/**
* @var array
*/
protected $options;
/**
* @var array|string
*/
protected $referencedFields;
/**
* @var string
*/
protected $referencedModel;
/**
* @var int
*/
protected $type;
public function __construct( int $type, string $referencedModel, mixed $fields, mixed $referencedFields, array $options = [] );
public function setIntermediateRelation( mixed $intermediateFields, string $intermediateModel, mixed $intermediateReferencedFields );
public function setIntermediateRelation( mixed $intermediateFields, string $intermediateModel, mixed $intermediateReferencedFields );
// Using a standard foreach
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
foreach ($robots as robot) {
echo robot->name, "\n";
}
// Using a while
$robots = Robots::find(
[
"type = 'virtual'",
"order" => "name",
]
);
$robots->rewind();
while ($robots->valid()) {
$robot = $robots->current();
echo $robot->name, "\n";
$robots->next();
}
const HYDRATE_ARRAYS = 1;
const HYDRATE_OBJECTS = 2;
const HYDRATE_RECORDS = 0;
const TYPE_RESULT_FULL = 0;
const TYPE_RESULT_PARTIAL = 1;
/**
* @var mixed|null
*/
protected $activeRow;
/**
* @var CacheInterface|null
*/
protected $cache;
/**
* @var int
*/
protected $count = ;
/**
* @var array
*/
protected $errorMessages;
/**
* @var int
*/
protected $hydrateMode = ;
/**
* @var bool
*/
protected $isFresh = true;
/**
* @var int
*/
protected $pointer = ;
/**
* @var mixed|null
*/
protected $row;
/**
* @var array|null
*/
protected $rows;
/**
* Phalcon\Db\ResultInterface or false for empty resultset
*
* @var ResultInterface|bool
*/
protected $result;
$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();
/**
* @var array
*/
protected $columnTypes;
/**
* Unserialised result-set hydrated all rows already. unserialise() sets
* disableHydration to true
*
* @var bool
*/
protected $disableHydration = false;
public function __construct( mixed $columnTypes, ResultInterface $result = null, mixed $cache = null );
/**
* @var array|string
*/
protected $columnMap;
/**
* @var ModelInterface|Row
*/
protected $model;
/**
* @var bool
*/
protected $keepSnapshots = false;
public function __construct( mixed $columnMap, mixed $model, mixed $result, mixed $cache = null, bool $keepSnapshots = bool );
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();
}
/**
* @var bool
*/
protected $activeTransaction = false;
/**
* @var AdapterInterface
*/
protected $connection;
/**
* @var bool
*/
protected $isNewTransaction = true;
/**
* @var ManagerInterface|null
*/
protected $manager;
/**
* @var array
*/
protected $messages;
/**
* @var ModelInterface|null
*/
protected $rollbackRecord;
/**
* @var bool
*/
protected $rollbackOnAbort = false;
/**
* @var bool
*/
protected $rollbackThrowException = false;
public function __construct( DiInterface $container, bool $autoBegin = bool, string $service = string );
public function rollback( string $rollbackMessage = null, ModelInterface $rollbackRecord = null ): bool;
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();
}
/**
* @var DiInterface|null
*/
protected $container;
/**
* @var bool
*/
protected $initialized = false;
/**
* @var int
*/
protected $number = ;
/**
* @var bool
*/
protected $rollbackPendent = true;
/**
* @var string
*/
protected $service = db;
/**
* @var array
*/
protected $transactions;
public function rollback( string $rollbackMessage = null, ModelInterface $rollbackRecord = null ): bool;
public 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 = bool ): ModelInterface;
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();
/**
* @var string
*/
protected $action = ;
/**
* @var string
*/
protected $controller = ;
/**
* @var string
*/
protected $defaultAction = ;
/**
* @var string
*/
protected $defaultController = ;
/**
* @var string
*/
protected $defaultModule = ;
/**
* @var string
*/
protected $defaultNamespace = ;
/**
* @var array
*/
protected $defaultParams;
/**
* @var ManagerInterface|null
*/
protected $eventsManager;
/**
* @var array
*/
protected $keyRouteNames;
/**
* @var array
*/
protected $keyRouteIds;
/**
* @var RouteInterface|null
*/
protected $matchedRoute;
/**
* @var array
*/
protected $matches;
/**
* @var string
*/
protected $module = ;
/**
* @var string
*/
protected $namespaceName = ;
/**
* @var array|string|null
*/
protected $notFoundPaths;
/**
* @var array
*/
protected $params;
/**
* @var bool
*/
protected $removeExtraSlashes = false;
/**
* @var array
*/
protected $routes;
/**
* @var bool
*/
protected $wasMatched = false;
public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null, int $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, int $position = static-constant-access ): RouteInterface;
public function addDelete( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addGet( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addHead( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addOptions( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPatch( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPost( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPurge( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPut( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addTrace( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function attach( RouteInterface $route, int $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
);
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;
}
);
/**
* @var string
*/
protected $actionSuffix = Action;
/**
* @var callable|string|null
*/
protected $actionPreformatCallback;
/**
* @var string
*/
protected $controllerSuffix = Controller;
/**
* @var array
*/
protected $handlers;
/**
* @var string
*/
protected $routePrefix = ;
public function addModuleResource( string $module, string $handler, string $prefix = null ): Annotations;
public function processActionAnnotation( string $module, string $namespaceName, string $controller, string $action, Annotation $annotation ): void;
// Array as callback
$annotationRouter->setActionPreformatCallback(
[
new Uncamelize(),
'__invoke'
]
);
// Function as callback
$annotationRouter->setActionPreformatCallback(
function ($action) {
return $action;
}
);
// String as callback
$annotationRouter->setActionPreformatCallback('strtolower');
// If empty method constructor called [null], sets uncamelize with - delimiter
$annotationRouter->setActionPreformatCallback();
$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);
/**
* @var callable|null
*/
protected $beforeMatch;
/**
* @var string|null
*/
protected $hostname;
/**
* @var array|string|null
*/
protected $paths;
/**
* @var string|null
*/
protected $prefix;
/**
* @var array
*/
protected $routes;
public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
protected function addRoute( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
$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);
public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
/**
* @var callable|null
*/
protected $beforeMatch;
/**
* @var string|null
*/
protected $compiledPattern;
/**
* @var array
*/
protected $converters;
/**
* @var GroupInterface|null
*/
protected $group;
/**
* @var string|null
*/
protected $hostname;
/**
* @var string
*/
protected $id = ;
/**
* @var array|string
*/
protected $methods;
/**
* @var callable|null
*/
protected $match;
/**
* @var string|null
*/
protected $name;
/**
* @var array
*/
protected $paths;
/**
* @var string
*/
protected $pattern;
/**
* @var int
*/
protected static $uniqueId = ;
$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);
}
);
public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null, int $position = static-constant-access ): RouteInterface;
public function addConnect( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addDelete( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addGet( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addHead( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addOptions( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPatch( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPost( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPurge( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addPut( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function addTrace( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
public function attach( RouteInterface $route, int $position = static-constant-access ): RouterInterface;
// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");
// Generate a URL for a predefined route
echo $url->get(
[
"for" => "blog-post",
"title" => "some-cool-stuff",
"year" => "2012",
]
);
/**
* @var null | string
*/
protected $baseUri;
/**
* @var null | string
*/
protected $basePath;
/**
* @var RouterInterface | null
*/
protected $router;
/**
* @var null | string
*/
protected $staticBaseUri;
public function get( mixed $uri = null, mixed $args = null, bool $local = null, mixed $baseUri = null ): string;
// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");
// Generate a URL for a predefined route
echo $url->get(
[
"for" => "blog-post",
"title" => "some-cool-stuff",
"year" => "2015",
]
);
// Generate a URL with GET arguments (/show/products?id=1&name=Carrots)
echo $url->get(
"show/products",
[
"id" => 1,
"name" => "Carrots",
]
);
// Generate an absolute URL by setting the third parameter as false.
echo $url->get(
"https://phalcon.io/",
null,
false
);
// Generate a URL for a static resource
echo $url->getStatic("img/logo.png");
// Generate a URL for a static predefined route
echo $url->getStatic(
[
"for" => "logo-cdn",
]
);
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();
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;
/**
* @var string
*/
protected $actionName;
/**
* @var array
*/
protected $activeRenderPaths;
/**
* @var string
*/
protected $basePath = ;
/**
* @var string
*/
protected $content = ;
/**
* @var string
*/
protected $controllerName;
/**
* @var int
*/
protected $currentRenderLevel = ;
/**
* @var bool
*/
protected $disabled = false;
/**
* @var array
*/
protected $disabledLevels;
/**
* @var array|bool
*/
protected $engines = false;
/**
* @var ManagerInterface|null
*/
protected $eventsManager;
/**
* @var string|null
*/
protected $layout;
/**
* @var string
*/
protected $layoutsDir = ;
/**
* @var string
*/
protected $mainView = index;
/**
* @var array
*/
protected $options;
/**
* @var array
*/
protected $params;
/**
* @var array|null
*/
protected $pickView;
/**
* @var string
*/
protected $partialsDir = ;
/**
* @var array
*/
protected $registeredEngines;
/**
* @var int
*/
protected $renderLevel = 5;
/**
* @var array
*/
protected $templatesAfter;
/**
* @var array
*/
protected $templatesBefore;
/**
* @var array
*/
protected $viewsDirs;
/**
* @var array
*/
protected $viewParams;
// 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 );
/**
* @var Compiler
*/
protected $compiler;
/**
* @var ManagerInterface|null
*/
protected $eventsManager;
/**
* @var array
*/
protected $macros;
/**
* @var array
*/
protected $options;
$compiler = new \Phalcon\Mvc\View\Engine\Volt\Compiler();
$compiler->compile("views/partials/header.volt");
require $compiler->getCompiledTemplatePath();
/**
* @var bool
*/
protected $autoescape = false;
/**
* @var int
*/
protected $blockLevel = ;
/**
* @var array|null
*
* TODO: Make array only?
*/
protected $blocks;
/**
* @var DiInterface|null
*/
protected $container;
/**
* @var string|null
*/
protected $compiledTemplatePath;
/**
* @var string|null
*/
protected $currentBlock;
/**
* @var string|null
*/
protected $currentPath;
/**
* @var int
*/
protected $exprLevel = ;
/**
* @var bool
*/
protected $extended = false;
/**
* @var array
*/
protected $extensions;
/**
* @var array|bool
*
* TODO: Make it always array
*/
protected $extendedBlocks;
/**
* @var array
*/
protected $filters;
/**
* @var int
*/
protected $foreachLevel = ;
/**
* @var array
*/
protected $forElsePointers;
/**
* @var array
*/
protected $functions;
/**
* @var int
*/
protected $level = ;
/**
* @var array
*/
protected $loopPointers;
/**
* @var array
*/
protected $macros;
/**
* @var array
*/
protected $options;
/**
* @var string
*/
protected $prefix = ;
/**
* @var ViewBaseInterface|null
*/
protected $view;
<?php
use Phalcon\Mvc\View\Engine\Volt\Compiler;
$compiler = new Compiler();
// {% set a = ['first': 1] %}
$source = [
"type" => 306,
"assignments" => [
[
"variable" => [
"type" => 265,
"value" => "a",
"file" => "eval code",
"line" => 1
],
"op" => 61,
"expr" => [
"type" => 360,
"left" => [
[
"expr" => [
"type" => 258,
"value" => "1",
"file" => "eval code",
"line" => 1
],
"name" => "first",
"file" => "eval code",
"line" => 1
]
],
"file" => "eval code",
"line" => 1
],
"file" => "eval code",
"line" => 1
]
]
];
echo $compiler->compileSet($source);
// <?php $a = ['first' => 1]; ?>
public function __construct( string $message = string, array $statement = [], int $code = int, \Exception $previous = null );
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,
]
);
/**
* @var string
*/
protected $activeRenderPath;
/**
* @var string
*/
protected $content;
/**
* @var EngineInterface[]|false
*/
protected $engines = false;
/**
* @var ManagerInterface|null
*/
protected $eventsManager;
/**
* @var array
*/
protected $options;
/**
* @var array
*/
protected $registeredEngines;
/**
* @var string
*/
protected $viewsDir;
/**
* @var array
*/
protected $viewParams;
// 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,
]
);