Phalcon mvc
注意
所有类都以前缀命名Phalcon
Mvc\Application¶
-
命名空间
Phalcon\Mvc
-
使用
Closure
Phalcon\Application\AbstractApplication
Phalcon\Di\DiInterface
Phalcon\Events\ManagerInterface
Phalcon\Http\ResponseInterface
Phalcon\Mvc\Application\Exception
Phalcon\Mvc\ModuleDefinitionInterface
Phalcon\Mvc\Router\RouteInterface
-
继承
AbstractApplication
-
实现
Phalcon\Mvc\Application
该组件封装了实例化所需每个组件并将其与其余部分集成以使MVC模式按预期运行背后的所有复杂操作。
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();
属性¶
/**
* @var bool
*/
protected $implicitView = true;
/**
* @var bool
*/
protected $sendCookies = true;
/**
* @var bool
*/
protected $sendHeaders = true;
方法¶
处理一个MVC请求 启用或禁用每次请求处理时发送cookies 启用或禁用每次请求处理时发送头信息 默认情况下。视图会隐式缓冲所有输出,您可以使用此方法完全禁用视图组件Mvc\Application\Exception¶
-
命名空间
Phalcon\Mvc\Application
-
使用
-
继承
\Phalcon\Application\Exception
-
实现
Phalcon\Mvc\Application\Exception
在 Phalcon\Mvc\Application 类中抛出的异常将使用此类
Mvc\Controller
¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Di\Injectable
-
继承
Injectable
-
实现
ControllerInterface
Phalcon\Mvc\Controller
每个应用程序控制器都应该继承此类,该类封装了所有控制器功能
控制器提供了模型和视图之间的“流程”。控制器负责处理来自网络浏览器的传入请求,向模型查询数据,并将这些数据传递给视图进行展示。
<?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",
]
);
}
}
方法¶
Phalcon\Mvc\Controller 构造函数Mvc\Controller\BindModelInterface
¶
-
命名空间
Phalcon\Mvc\Controller
-
使用
-
继承
-
实现
Phalcon\Mvc\Controller\BindModelInterface
Phalcon\Mvc\Controller 的接口
方法¶
返回与此控制器关联的模型名称Mvc\ControllerInterface
¶
-
命名空间
Phalcon\Mvc
-
使用
-
继承
-
实现
Phalcon\Mvc\ControllerInterface
控制器处理器的接口
Mvc\Dispatcher¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Dispatcher\AbstractDispatcher
Phalcon\Events\ManagerInterface
Phalcon\Http\ResponseInterface
Phalcon\Mvc\Dispatcher\Exception
-
继承
BaseDispatcher
-
实现
DispatcherInterface
分发是获取请求对象、提取其中包含的模块名、控制器名、动作名以及可选参数,然后实例化一个控制器并调用该控制器的一个动作的过程。
$di = new \Phalcon\Di\Di();
$dispatcher = new \Phalcon\Mvc\Dispatcher();
$dispatcher->setDI($di);
$dispatcher->setControllerName("posts");
$dispatcher->setActionName("index");
$dispatcher->setParams([]);
$controller = $dispatcher->dispatch();
属性¶
//
protected $defaultAction = index;
//
protected $defaultHandler = index;
//
protected $handlerSuffix = Controller;
方法¶
将执行流程转发到另一个控制器/动作。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¶
-
命名空间
Phalcon\Mvc\Dispatcher
-
使用
-
继承
\Phalcon\Dispatcher\Exception
-
实现
Phalcon\Mvc\Dispatcher\Exception
在 Phalcon\Mvc\Dispatcher 中抛出的异常将使用此类
Mvc\DispatcherInterface
¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Dispatcher\DispatcherInterface
-
继承
DispatcherInterfaceBase
-
实现
Phalcon\Mvc\DispatcherInterface
Phalcon\Mvc\Dispatcher 的接口
方法¶
返回调度器中的活动控制器 获取最后调度的控制器名称 返回最后分发的控制器 设置要调度的控制器名称 设置默认控制器后缀 设置默认控制器名Mvc\EntityInterface
¶
-
命名空间
Phalcon\Mvc
-
使用
-
继承
-
实现
Phalcon\Mvc\EntityInterface
Phalcon\Mvc\Collection 和 Phalcon\Mvc\Model 的接口
方法¶
按属性名读取属性值 按属性名写入属性值Mvc\Micro¶
-
命名空间
Phalcon\Mvc
-
使用
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
-
继承
Injectable
-
实现
ArrayAccess
EventsAwareInterface
Phalcon\Mvc\Micro
使用 Phalcon,您可以创建类似“微型框架”的应用程序。通过这样做,您只需编写少量代码即可创建PHP应用程序。微型应用适合以实用方式快速构建小型应用程序、API和原型。
$app = new \Phalcon\Mvc\Micro();
$app->get(
"/say/welcome/{name}",
function ($name) {
echo "<h1>Welcome $name!</h1>";
}
);
$app->handle("/say/welcome/Phalcon");
属性¶
/**
* @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;
方法¶
Phalcon\Mvc\Micro 构造函数 添加一个 'after' 中间件,在执行路由后调用 添加一个 afterBinding 中间件,在模型绑定后调用 添加一个 before 中间件,在执行路由前调用 将路由映射到处理器上,只有当 HTTP 方法为 DELETE 时才匹配 设置一个在处理路由时抛出异常时调用的处理器 添加一个 'finish' 中间件,当请求结束时调用 将路由映射到处理器上,只有当 HTTP 方法为 GET 时才匹配 返回用于匹配路由的处理器 返回绑定实例中的绑定模型 返回内部事件管理器 返回附加到应用程序的内部处理器 获取模型绑定器 返回已执行处理器返回的值 返回应用程序使用的内部路由器 从 DI 获取服务 从 DI 获取共享服务 处理整个请求 检查 DI 中是否注册了服务 将路由映射到处理器上,只有当 HTTP 方法为 HEAD 时才匹配 将路由映射到没有 HTTP 方法限制的处理器 挂载一组处理器 设置当路由器不匹配任何定义的路由时调用的处理器 使用数组语法检查内部服务容器中是否注册了某个服务 允许使用数组语法从内部服务容器中获取共享服务 允许使用数组语法在内部服务容器中注册共享服务 使用数组语法从内部服务容器中移除服务 映射一个路由到仅在 HTTP 方法为 OPTIONS 时才匹配的处理程序 映射一个路由到仅在 HTTP 方法为 PATCH 时才匹配的处理程序 映射一个路由到仅在 HTTP 方法为 POST 时才匹配的处理程序 映射一个路由到仅在 HTTP 方法为 PUT 时才匹配的处理程序 外部设置与路由匹配时必须调用的处理器 设置DependencyInjector容器 设置事件管理器 设置模型绑定器 添加一个自定义'response'处理器,代替默认响应处理器调用public function setService( string $serviceName, mixed $definition, bool $shared = bool ): ServiceInterface;
Mvc\Micro\Collection¶
-
命名空间
Phalcon\Mvc\Micro
-
使用
-
继承
-
实现
CollectionInterface
Phalcon\Mvc\Micro\Collection
将 Micro-Mvc 处理程序分组成控制器
$app = new \Phalcon\Mvc\Micro();
$collection = new Collection();
$collection->setHandler(
new PostsController()
);
$collection->get("/posts/edit/{id}", "edit");
$app->mount($collection);
属性¶
/**
* @var callable
*/
protected $handler;
/**
* @var array
*/
protected $handlers;
/**
* @var bool
*/
protected $lazy = false;
/**
* @var string
*/
protected $prefix = ;
方法¶
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
¶
-
命名空间
Phalcon\Mvc\Micro
-
使用
-
继承
-
实现
Phalcon\Mvc\Micro\CollectionInterface
Phalcon\Mvc\Micro\Collection 的接口
方法¶
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¶
-
命名空间
Phalcon\Mvc\Micro
-
使用
-
继承
\Exception
-
实现
Phalcon\Mvc\Micro 中抛出的异常将使用此类
Mvc\Micro\LazyLoader¶
-
命名空间
Phalcon\Mvc\Micro
-
使用
Phalcon\Mvc\Model\BinderInterface
-
继承
-
实现
Phalcon\Mvc\Micro\LazyLoader
使用自动加载实现 Mvc\Micro 处理程序的延迟加载
属性¶
方法¶
Phalcon\Mvc\Micro\LazyLoader 构造函数public function callMethod( string $method, mixed $arguments, BinderInterface $modelBinder = null );
Mvc\Micro\MiddlewareInterface
¶
-
命名空间
Phalcon\Mvc\Micro
-
使用
Phalcon\Mvc\Micro
-
继承
-
实现
允许在类中实现 Phalcon\Mvc\Micro 中间件
方法¶
调用中间件Mvc\Model
¶
-
命名空间
Phalcon\Mvc
-
使用
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\Support\Collection
Phalcon\Support\Collection\CollectionInterface
Serializable
-
继承
AbstractInjectionAware
-
实现
EntityInterface
JsonSerializable
ModelInterface
ResultInterface
Serializable
Phalcon\Mvc\Model
Phalcon\Mvc\Model 将业务对象和数据库表连接起来,以创建一个可持久化的领域模型,在其中逻辑和数据被整合在一起呈现。这是对象关系映射(ORM)的一个实现。
模型表示应用程序的信息(数据)以及操作这些数据的规则。模型主要用于管理与相应数据库表交互的规则。在大多数情况下,数据库中的每个表都会对应应用程序中的一个模型。大部分应用程序的业务逻辑将集中在模型中。
Phalcon\Mvc\Model 是使用 Zephir/C 语言为 PHP 编写的第一个 ORM,它在与数据库交互时为开发人员提供了高性能,同时也很容易使用。
$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!";
}
常量¶
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;
属性¶
/**
* @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;
方法¶
当某个方法未实现时处理方法调用 当某个静态方法未实现时处理方法调用final 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",
]
);
简单查询返回值为浮点数,当使用 GROUP 条件时则返回 ResultsetInterface 实例。结果将包含每个组的平均值。
// 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,
]
);
返回一个整数用于简单查询,或当使用 GROUP 条件时返回一个 ResultsetInterface 实例。结果将包含每组的数量。
// 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()
查询符合指定条件的一组记录 // 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
仅当记录此前是通过模型且没有任何额外参数的情况下获取时,才返回 true
$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";
true
成功时返回false
。 <?php
use MyApp\Models\Invoices;
$invoice = Invoices::findFirst('inv_id = 4');
$invoice->inv_total = 120;
$invoice->update();
注意
当通过findFirst()
查询记录时,你需要获取完整的对象(没有columns
定义),但还需要通过主键进行检索。如果不这样做,ORM 将发出一个INSERT
而不是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
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Mvc\ModelInterface
-
继承
-
实现
BehaviorInterface
Phalcon\Mvc\Model\Behavior
ORM行为的一个可选基类
属性¶
方法¶
Phalcon\Mvc\Model\Behavior 当调用模型上缺失的方法时作为备用方案 此方法从EventsManager接收通知 Returns the behavior options related to an event 检查行为是否应在某些事件上采取行动。Mvc\Model\Behavior\SoftDelete¶
-
命名空间
Phalcon\Mvc\Model\Behavior
-
使用
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Behavior
Phalcon\Mvc\Model\Exception
-
继承
Behavior
-
实现
Phalcon\Mvc\Model\Behavior\SoftDelete
不是永久删除记录,而是标记记录为已删除,改变标志列的值
方法¶
监听来自模型管理器的通知Mvc\Model\Behavior\Timestampable¶
-
命名空间
Phalcon\Mvc\Model\Behavior
-
使用
Closure
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Behavior
Phalcon\Mvc\Model\Exception
-
继承
Behavior
-
实现
Phalcon\Mvc\Model\Behavior\Timestampable
允许自动更新模型的属性,在记录创建或更新时保存日期时间
方法¶
监听来自模型管理器的通知Mvc\Model\BehaviorInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Mvc\ModelInterface
-
继承
-
实现
Phalcon\Mvc\Model\BehaviorInterface
Phalcon\Mvc\Model\Behavior的接口
方法¶
当模型中缺少某个方法时调用该方法 此方法从EventsManager接收通知Mvc\Model\Binder¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Closure
Phalcon\Cache\Adapter\AdapterInterface
Phalcon\Mvc\Controller\BindModelInterface
Phalcon\Mvc\Model\Binder\BindableInterface
ReflectionFunction
ReflectionMethod
-
继承
-
实现
BinderInterface
Phalcon\Mvc\Model\Binder
将模型绑定到处理器参数中的类
属性¶
/**
* 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;
方法¶
Phalcon\Mvc\Model\Binder构造函数public 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
¶
-
命名空间
Phalcon\Mvc\Model\Binder
-
使用
-
继承
-
实现
Phalcon\Mvc\Model\Binder\BindableInterface
可绑定类的接口
方法¶
返回与此类关联的模型名称或模型名称及参数键Mvc\Model\BinderInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Cache\Adapter\AdapterInterface
-
继承
-
实现
Phalcon\Mvc\Model\BinderInterface
Phalcon\Mvc\Model\Binder的接口
方法¶
public function bindToHandler( object $handler, array $params, string $cacheKey, string $methodName = null ): array;
Mvc\Model\Criteria¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Db\Column
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\Model\Query\BuilderInterface
-
继承
-
实现
CriteriaInterface
InjectionAwareInterface
该类用于构建Phalcon\Mvc\Model::find() 和 Phalcon\Mvc\Model::findFirst() 所需的数组参数,使用面向对象的接口来实现
<?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();
属性¶
/**
* @var array
*/
protected $bindParams;
/**
* @var array
*/
protected $bindTypes;
/**
* @var int
*/
protected $hiddenParamNumber = ;
/**
* @var string|null
*/
protected $model;
/**
* @var array
*/
protected $params;
方法¶
public function andWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
string
或者一个array
字符串的数组。如果参数是一个(单一、非嵌套)字符串,其内容可以用逗号分隔指定一个或多个列,就像使用 SQL select 语句一样。你可以使用别名、聚合函数等。如果你需要引用其他模型你将需要使用它们的命名空间来引用它们。 当使用数组作为参数时,你需要为每个数组元素指定一个字段。如果数组中定义了非数字键,它将在查询中用作别名
<?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",
]
);
$invoices = Invoices::query() ->where("inv_cst_id = :customerId:") ->bind(["customerId" => 1]) ->createBuilder();
$invoices = Invoices::query() ->where("inv_cst_id = :customerId:") ->bind(["customerId" => 1]) ->createBuilder();
设置 SELECT DISTINCT / SELECT ALL 标志 使用通过条件构建的参数执行find操作 添加"for_update"参数到查询条件public static function fromInput( DiInterface $container, string $modelName, array $data, string $operator = string ): CriteriaInterface;
- 如果仅设置了'limit'而没有设置'offset'则为整数
- 如果设置了offset和limit,则为包含'number'和'offset'键的数组
- 如果未设置limit,则为NULL
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;
Mvc\Model\CriteriaInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Di\DiInterface
-
继承
-
实现
Phalcon\Mvc\Model\CriteriaInterface
Phalcon\Mvc\Model\Criteria接口
方法¶
public function andWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
- 如果仅设置了'limit'而没有设置'offset'则为整数
- 如果设置了offset和limit,则为包含'number'和'offset'键的数组
- 如果未设置limit,则为NULL
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¶
-
命名空间
Phalcon\Mvc\Model
-
使用
-
继承
\Exception
-
实现
Phalcon\Mvc\Model\Exception
抛出在Phalcon\Mvc\Model*类中的异常将使用此类
Mvc\Model\Manager¶
-
命名空间
Phalcon\Mvc\Model
-
使用
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
-
继承
-
实现
EventsAwareInterface
InjectionAwareInterface
ManagerInterface
Phalcon\Mvc\Model\Manager
此组件控制模型的初始化,记录应用程序中不同模型之间的关系。
通过依赖注入器/服务容器(如Phalcon\Di\Di)将ModelsManager注入到模型中。
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;
方法¶
销毁当前PHQL缓存 Binds a behavior to a modelpublic 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
$param string $prefix
为模型设置映射的数据库模式。 为模型设置映射的数据源。 为模型设置读取连接服务。 Stores a reusable record in the internal listpublic function setWriteConnectionService( ModelInterface $model, string $connectionService ): void;
protected function getConnection( ModelInterface $model, array $connectionServices ): AdapterInterface;
Mvc\Model\ManagerInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Query\BuilderInterface
Phalcon\Mvc\Model\Query\StatusInterface
-
继承
-
实现
Phalcon\Mvc\Model\ManagerInterface
Interface for Phalcon\Mvc\Model\Manager
方法¶
Binds a behavior to a modelpublic 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 );
Mvc\Model\MetaData
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
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
-
继承
-
实现
InjectionAwareInterface
MetaDataInterface
Phalcon\Mvc\Model\MetaData
因为 Phalcon\Mvc\Model 需要元数据,如字段名称、数据类型、主键等。该组件收集这些信息并存储,供 Phalcon\Mvc\Model 进一步查询使用。Phalcon\Mvc\Model\MetaData 也可以使用适配器来临时或永久存储元数据。
标准的 Phalcon\Mvc\Model\MetaData 可用于查询模型属性:
$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;
方法¶
返回内部缓存适配器。 返回表属性名(字段) 返回必须忽略的 INSERT SQL 生成属性 返回必须忽略的 UPDATE SQL 生成属性 返回属性及其绑定数据类型 如果有的话返回列映射 返回DependencyInjector容器 返回属性及其数据类型 返回类型为数值的属性 返回具有默认值的属性及其默认值 返回允许空字符串的属性 返回标识字段的名称(如果存在一个) 返回不属于主键的字段数组 返回非空属性的数组 返回属于主键的字段数组 如果有的话返回反向列映射 返回获取元数据的策略 检查模型是否具有某个属性 检查内部元数据容器是否为空 从适配器读取元数据 读取特定模型的有序/反向列映射 使用 MODEL_* 常量读取特定模型的列映射信息 读取特定模型的完整元数据 读取特定模型的元数据 重置内部元数据以便重新生成它 设置必须从 INSERT SQL 生成中忽略的属性 设置必须从 UPDATE SQL 生成中忽略的属性 设置DependencyInjector容器 设置允许空字符串值的属性 设置元数据提取策略 将元数据写入适配器 使用 MODEL_* 常量为特定模型写入元数据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 );
Mvc\Model\MetaData\Apcu¶
-
命名空间
Phalcon\Mvc\Model\MetaData
-
使用
Phalcon\Cache\AdapterFactory
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
继承
MetaData
-
实现
Phalcon\Mvc\Model\MetaData\Apcu
将模型元数据存储在 APCu 缓存中。如果 Web 服务器重启,数据将被清除
默认元数据存储 48 小时(172800 秒)
您可以通过打印 apcu_fetch('$PMM$') 或 apcu_fetch('$PMM$my-app-id') 来查询元数据
$metaData = new \Phalcon\Mvc\Model\MetaData\Apcu(
[
"prefix" => "my-app-id",
"lifetime" => 86400,
]
);
方法¶
Phalcon\Mvc\Model\MetaData\Apcu 构造函数Mvc\Model\MetaData\Libmemcached¶
-
命名空间
Phalcon\Mvc\Model\MetaData
-
使用
Phalcon\Cache\AdapterFactory
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
继承
MetaData
-
实现
Phalcon\Mvc\Model\MetaData\Libmemcached
将模型元数据存储在 Memcache 中。
默认元数据存储 48 小时(172800 秒)
方法¶
Phalcon\Mvc\Model\MetaData\Libmemcached 构造函数 清空 Memcache 数据并重置内部元数据以便重新生成Mvc\Model\MetaData\Memory¶
-
命名空间
Phalcon\Mvc\Model\MetaData
-
使用
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
继承
MetaData
-
实现
Phalcon\Mvc\Model\MetaData\Memory
将模型元数据存储在内存中。请求结束后数据将被清除
方法¶
Phalcon\Mvc\Model\MetaData\Memory 构造函数 从临时内存读取元数据 将元数据写入临时内存Mvc\Model\MetaData\Redis¶
-
命名空间
Phalcon\Mvc\Model\MetaData
-
使用
Phalcon\Cache\AdapterFactory
Phalcon\Mvc\Model\MetaData
-
继承
MetaData
-
实现
Phalcon\Mvc\Model\MetaData\Redis
将模型元数据存储在 Redis 中。
默认元数据存储 48 小时(172800 秒)
use Phalcon\Mvc\Model\MetaData\Redis;
$metaData = new Redis(
[
"host" => "127.0.0.1",
"port" => 6379,
"persistent" => 0,
"lifetime" => 172800,
"index" => 2,
]
);
方法¶
Phalcon\Mvc\Model\MetaData\Redis 构造函数 清空 Redis 数据并重置内部元数据以便重新生成Mvc\Model\MetaData\Strategy\Annotations¶
-
命名空间
Phalcon\Mvc\Model\MetaData\Strategy
-
使用
Phalcon\Db\Column
Phalcon\Di\DiInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
继承
-
实现
StrategyInterface
该文件是Phalcon框架的一部分。
(c) Phalcon团队team@phalcon.io
有关完整的版权和许可信息,请查看随此源代码分发的LICENSE.txt文件。
方法¶
读取模型的列映射,这无法推断 元数据是通过读取数据库信息模式中的列描述来获得的Mvc\Model\MetaData\Strategy\Introspection¶
-
命名空间
Phalcon\Mvc\Model\MetaData\Strategy
-
使用
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Db\Column
Phalcon\Di\DiInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
继承
-
实现
StrategyInterface
Phalcon\Mvc\Model\MetaData\Strategy\Introspection
查询表元数据以检测模型的元数据
方法¶
读取模型的列映射,这无法推断 元数据是通过读取数据库信息模式中的列描述来获得的Mvc\Model\MetaData\Strategy\StrategyInterface
¶
-
命名空间
Phalcon\Mvc\Model\MetaData\Strategy
-
使用
Phalcon\Di\DiInterface
Phalcon\Mvc\ModelInterface
-
继承
-
实现
该文件是Phalcon框架的一部分。
(c) Phalcon团队team@phalcon.io
有关完整的版权和许可信息,请查看随此源代码分发的LICENSE.txt文件。
方法¶
读取模型的列映射,这无法推断@todo 尚未实现
元数据是通过读取数据库信息模式中的列描述来获得的Mvc\Model\MetaData\Stream¶
-
命名空间
Phalcon\Mvc\Model\MetaData
-
使用
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\MetaData
-
继承
MetaData
-
实现
Phalcon\Mvc\Model\MetaData\Stream
将模型元数据存储在 PHP 文件中。
属性¶
方法¶
Phalcon\Mvc\Model\MetaData\Files 构造函数 从文件读取元数据 将元数据写入文件Mvc\Model\MetaDataInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
-
继承
-
实现
Phalcon\Mvc\Model\MetaDataInterface
Phalcon\Mvc\Model\MetaData 的接口
方法¶
返回表属性名(字段) 返回必须忽略的 INSERT SQL 生成属性 返回必须忽略的 UPDATE SQL 生成属性 返回属性及其绑定数据类型 如果有的话返回列映射 返回属性及其数据类型 返回类型为数值的属性 返回具有默认值的属性及其默认值 返回允许空字符串的属性 返回标识字段的名称(如果存在一个) 返回不属于主键的字段数组 返回非空属性的数组 返回属于主键的字段数组 如果有的话返回反向列映射 返回获取元数据的策略 检查模型是否具有某个属性 检查内部元数据容器是否为空 从适配器读取元数据 读取特定模型的有序/反向列映射 使用 MODEL_* 常量读取特定模型的列映射信息 读取特定模型的元数据 使用 MODEL_* 常量读取特定模型的元数据 重置内部元数据以便重新生成它 设置必须从 INSERT SQL 生成中忽略的属性 设置必须从 UPDATE SQL 生成中忽略的属性 设置允许空字符串值的属性 设置元数据提取策略 将元数据写入适配器 使用 MODEL_* 常量为特定模型写入元数据Mvc\Model\Query¶
-
命名空间
Phalcon\Mvc\Model
-
使用
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
-
继承
-
实现
InjectionAwareInterface
QueryInterface
Phalcon\Mvc\Model\Query
此类接受 PHQL 中间表示并执行它。
$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;
Mvc\Model\Query\Builder¶
-
命名空间
Phalcon\Mvc\Model\Query
-
使用
Phalcon\Db\Column
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\Model\Exception
Phalcon\Mvc\Model\QueryInterface
-
继承
-
实现
BuilderInterface
InjectionAwareInterface
使用面向对象接口帮助创建 PHQL 查询
$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;
方法¶
Phalcon\Mvc\Model\Query\Builder 构造函数 添加一个模型参与查询// 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;
string
或者一个array
字符串的数组。如果参数是一个(单一、非嵌套)字符串,其内容可以用逗号分隔指定一个或多个列,就像使用 SQL select 语句一样。你可以使用别名、聚合函数等。如果你需要引用其他模型你将需要使用它们的命名空间来引用它们。 当使用数组作为参数时,你需要为每个数组元素指定一个字段。如果数组中定义了非数字键,它将在查询中用作别名
<?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;
Mvc\Model\Query\BuilderInterface
¶
-
命名空间
Phalcon\Mvc\Model\Query
-
使用
Phalcon\Mvc\Model\QueryInterface
-
继承
-
实现
Phalcon\Mvc\Model\Query\BuilderInterface
Phalcon\Mvc\Model\Query\Builder 的接口
常量¶
方法¶
添加一个模型参与查询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;
string
或者一个array
字符串的数组。如果参数是一个(单一、非嵌套)字符串,其内容可以用逗号分隔指定一个或多个列,就像使用 SQL select 语句一样。你可以使用别名、聚合函数等。如果你需要引用其他模型你将需要使用它们的命名空间来引用它们。 当使用数组作为参数时,你需要为每个数组元素指定一个字段。如果数组中定义了非数字键,它将在查询中用作别名
<?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;
Mvc\Model\Query\Lang
¶
-
命名空间
Phalcon\Mvc\Model\Query
-
使用
-
继承
-
实现
Phalcon\Mvc\Model\Query\Lang
PHQL 被实现为一个解析器(用 C 编写),该解析器将语法翻译为目标 RDBMS 的语法。它允许 Phalcon 向开发人员提供统一的 SQL 语言,同时在内部根据与模型关联的 RDBMS 类型将 PHQL 指令翻译为最优化的 SQL 指令。
为了实现尽可能高的性能,我们编写了一个使用与 SQLite 相同技术的解析器。该技术提供了一个小型内存中的解析器,具有非常低的内存占用,并且是线程安全的。
use Phalcon\Mvc\Model\Query\Lang;
$intermediate = Lang::parsePHQL(
"SELECT r.* FROM Robots r LIMIT 10"
);
方法¶
解析一个 PHQL 语句并返回中间表示(IR)Mvc\Model\Query\Status¶
-
命名空间
Phalcon\Mvc\Model\Query
-
使用
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
继承
-
实现
StatusInterface
Phalcon\Mvc\Model\Query\Status
此类表示由类似 INSERT、UPDATE 或 DELETE 的 PHQL 语句返回的状态。它提供了失败时执行操作的模型所生成的上下文信息和相关消息。
$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";
}
属性¶
方法¶
Phalcon\Mvc\Model\Query\Status 返回由于操作失败而产生的消息 返回执行操作的模型 允许检查已执行的操作是否成功Mvc\Model\Query\StatusInterface
¶
-
命名空间
Phalcon\Mvc\Model\Query
-
使用
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
继承
-
实现
Phalcon\Mvc\Model\Query\StatusInterface
Phalcon\Mvc\Model\Query\Status 的接口
方法¶
返回由操作失败所产生的消息 返回执行操作的模型 允许检查已执行的操作是否成功Mvc\Model\QueryInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Mvc\ModelInterface
-
继承
-
实现
Phalcon\Mvc\Model\QueryInterface
Phalcon\Mvc\Model\Query 的接口
方法¶
设置查询的缓存参数 执行已解析的 PHQL 语句 返回默认绑定参数 返回默认绑定类型 返回当前缓存选项 执行查询并返回第一个结果 返回由内部 PHQL 生成的 SQL(仅适用于 SELECT 语句) 检查查询是否被设置为只获取结果集中的第一行 解析 Phalcon\Mvc\Model\Query\Lang 生成的中间代码,生成另一个可由 Phalcon\Mvc\Model\Query 执行的中间表示 设置默认绑定参数 设置默认绑定参数 设置 SHARED LOCK 子句 告诉查询是否只应返回结果集中的第一行Mvc\Model\Relation¶
-
命名空间
Phalcon\Mvc\Model
-
使用
-
继承
-
实现
RelationInterface
Phalcon\Mvc\Model\Relation
此类表示两个模型之间的关系
常量¶
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 );
Mvc\Model\RelationInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
-
继承
-
实现
Phalcon\Mvc\Model\RelationInterface
Phalcon\Mvc\Model\Relation 的接口
方法¶
返回字段 返回外键配置 获取 has-*-through 关联的中间字段 获取 has-*-through 关联的中间模型 获取 has-*-through 关联的中间引用字段 按指定名称返回一个选项。如果选项不存在则返回 null 返回选项 返回在获取关联记录时必须始终使用的参数 返回引用字段 返回引用模型 返回关系类型 检查关系是否充当外键 检查通过获取 belongs-to/has-many 返回的记录是否在当前请求期间被隐式缓存 检查该关系是否为“多对多”关系public function setIntermediateRelation( mixed $intermediateFields, string $intermediateModel, mixed $intermediateReferencedFields );
Mvc\Model\ResultInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Mvc\ModelInterface
-
继承
-
实现
Phalcon\Mvc\Model\ResultInterface
所有作为基对象传递给结果集的单个对象都必须实现此接口
方法¶
设置对象状态Mvc\Model\Resultset
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
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
-
继承
-
实现
ArrayAccess
Countable
Iterator
JsonSerializable
ResultsetInterface
SeekableIterator
Serializable
Phalcon\Mvc\Model\Resultset
此组件允许 Phalcon\Mvc\Model 返回大规模的结果集,同时保持最小的内存消耗。结果集可以使用标准的 foreach 或 while 语句遍历。如果对结果集进行序列化,它会将所有行转储到一个大数组中。然后反序列化将像序列化之前一样恢复这些行。
// 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;
方法¶
Phalcon\Mvc\Model\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¶
-
命名空间
Phalcon\Mvc\Model\Resultset
-
使用
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
-
继承
Resultset
-
实现
ResultsetInterface
Phalcon\Mvc\Model\Resultset\Complex
复合结果集可以包括完整对象和标量值。此类在需要时构建每一个复合行
属性¶
/**
* @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 );
Mvc\Model\Resultset\Simple¶
-
命名空间
Phalcon\Mvc\Model\Resultset
-
使用
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
-
继承
Resultset
-
实现
Phalcon\Mvc\Model\Resultset\Simple
简单结果集仅包含完整的对象。此类在需要时构建每个完整对象
属性¶
/**
* @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 );
Mvc\Model\ResultsetInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Closure
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
继承
-
实现
Phalcon\Mvc\Model\ResultsetInterface
Phalcon\Mvc\Model\Resultset 的接口定义
方法¶
删除结果集中的每一条记录 过滤结果集,仅返回开发者需要的内容 返回结果集关联的缓存 获取结果集的第一行 返回当前的 hydration 模式 获取结果集的最后一行 返回批量操作所产生的错误信息 返回结果集正在使用的内部数据检索类型 判断该结果集是新的还是旧的缓存数据 设置结果集的 hydration 模式 设置判断结果集是否为新的或者旧的缓存数据 将整个结果集作为数组返回,若结果集包含大量行,可能会占用比当前更多的内存。 更新结果集中的每一条记录Mvc\Model\Row¶
-
命名空间
Phalcon\Mvc\Model
-
使用
ArrayAccess
JsonSerializable
Phalcon\Mvc\EntityInterface
Phalcon\Mvc\ModelInterface
-
继承
\stdClass
-
实现
ArrayAccess
EntityInterface
JsonSerializable
ResultInterface
此组件允许 Phalcon\Mvc\Model 返回没有关联实体的行。此对象实现了 ArrayAccess 接口,可用于通过 object->x 或 array[x] 的方式访问对象。
方法¶
序列化对象以供json_encode使用 检查行中是否存在指定的偏移量 获取行内特定位置的记录 行不能被更改。该功能仅为了满足 ArrayAccess 接口定义而实现 行不能被更改。该功能仅为了满足 ArrayAccess 接口定义而实现 按属性名读取属性值 设置当前对象的状态 将实例以数组形式表示出来 按属性名写入属性值Mvc\Model\Transaction¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Di\DiInterface
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\TransactionInterface
Phalcon\Mvc\Model\Transaction\Failed
Phalcon\Mvc\Model\Transaction\ManagerInterface
-
继承
-
实现
TransactionInterface
Phalcon\Mvc\Model\Transaction
事务是一个保护块,在其中 SQL 语句只有在全部成功作为一个原子操作的情况下才会永久生效。Phalcon\Transaction 预计与 Phalcon_Model_Base 一起使用。应使用 Phalcon\Transaction\Manager 创建 Phalcon 事务。
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;
Mvc\Model\Transaction\Exception¶
-
命名空间
Phalcon\Mvc\Model\Transaction
-
使用
-
继承
\Phalcon\Mvc\Model\Exception
-
实现
Phalcon\Mvc\Model\Transaction\Exception
Phalcon\Mvc\Model\Transaction 中抛出的异常将使用这个类
Mvc\Model\Transaction\Failed¶
-
命名空间
Phalcon\Mvc\Model\Transaction
-
使用
Phalcon\Messages\MessageInterface
Phalcon\Mvc\ModelInterface
-
继承
Exception
-
实现
Phalcon\Mvc\Model\Transaction\Failed
发生失败时会抛出此类,用于退出 try/catch 块处理独立事务
属性¶
方法¶
Phalcon\Mvc\Model\Transaction\Failed 构造函数 返回阻止事务继续执行的验证记录信息 返回阻止事务继续执行的验证记录信息Mvc\Model\Transaction\Manager¶
-
命名空间
Phalcon\Mvc\Model\Transaction
-
使用
Phalcon\Di\Di
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\Model\Transaction
Phalcon\Mvc\Model\TransactionInterface
-
继承
-
实现
InjectionAwareInterface
ManagerInterface
Phalcon\Mvc\Model\Transaction\Manager
一个事务作用于单一的数据库连接。如果你有多个特定类别的数据库,事务不会保护它们之间的交互。
该类管理构成事务的对象。一个事务会产生一个唯一的连接,并传递给事务中的每个对象部分。
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;
方法¶
Phalcon\Mvc\Model\Transaction\Manager 构造函数 从管理器中移除所有事务 提交管理器内的活动事务 返回一个新的 \Phalcon\Mvc\Model\Transaction 或一个已经创建的事务。此方法注册一个关闭函数以回滚活动连接 返回依赖注入容器 返回用于隔离事务的数据库服务 创建/返回一个新的事务或已存在的事务 检查事务管理器是否注册了一个关闭函数来清理挂起的事务 检查管理器是否有活动的事务 通知管理器关于已提交的事务 通知管理器关于已回滚的事务 回滚管理器内的活动事务。Collect 将从管理器中移除事务 回滚管理器内的活动事务 设置依赖注入容器 设置用于运行隔离事务的数据库服务 设置事务管理器是否必须注册一个关闭函数来清理挂起的事务 从 TransactionManager 中移除事务Mvc\Model\Transaction\ManagerInterface
¶
-
命名空间
Phalcon\Mvc\Model\Transaction
-
使用
Phalcon\Mvc\Model\TransactionInterface
-
继承
-
实现
Phalcon\Mvc\Model\Transaction\ManagerInterface
Phalcon\Mvc\Model\Transaction\Manager 的接口
方法¶
从管理器中移除所有事务 提交管理器内的活动事务 返回一个新的 \Phalcon\Mvc\Model\Transaction 或一个已经创建的事务 返回用于隔离事务的数据库服务 检查事务管理器是否注册了一个关闭函数来清理挂起的事务 检查管理器是否有活动的事务 通知管理器关于已提交的事务 通知管理器关于已回滚的事务 回滚管理器内的活动事务。Collect 将从管理器中移除事务 回滚管理器内的活动事务 设置用于运行隔离事务的数据库服务 设置事务管理器是否必须注册一个关闭函数来清理挂起的事务Mvc\Model\TransactionInterface
¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model\Transaction\ManagerInterface
-
继承
-
实现
Phalcon\Mvc\Model\TransactionInterface
Phalcon\Mvc\Model\Transaction 的接口
方法¶
启动事务 提交事务 返回与事务相关的连接 返回上次保存尝试中的验证消息 检查事务是否由事务管理器管理 检查内部连接是否处于活动事务中public function rollback( string $rollbackMessage = null, ModelInterface $rollbackRecord = null ): bool;
Mvc\Model\ValidationFailed¶
-
命名空间
Phalcon\Mvc\Model
-
使用
Phalcon\Messages\Message
Phalcon\Mvc\ModelInterface
-
继承
Exception
-
实现
Phalcon\Mvc\Model\ValidationFailed
当模型保存记录失败时会生成此异常。Phalcon\Mvc\Model 必须配置为此行为
属性¶
方法¶
Phalcon\Mvc\Model\ValidationFailed 构造函数 返回验证过程中产生的完整消息组 返回生成消息的模型Mvc\ModelInterface
¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Db\Adapter\AdapterInterface
Phalcon\Di\DiInterface
Phalcon\Messages\MessageInterface
Phalcon\Mvc\Model\CriteriaInterface
Phalcon\Mvc\Model\MetaDataInterface
Phalcon\Mvc\Model\Resultset
Phalcon\Mvc\Model\ResultsetInterface
Phalcon\Mvc\Model\TransactionInterface
-
继承
-
实现
Phalcon\Mvc\ModelInterface
Phalcon\Mvc\Model 的接口
方法¶
在验证过程中添加自定义消息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;
返回一个整数用于简单查询,或当使用 GROUP 条件时返回一个 ResultsetInterface 实例。结果将包含每组的数量。
插入一个模型实例。如果该实例已经在持久化中存在,则会抛出异常。成功返回 true,否则返回 false。 删除模型实例。成功时返回true,否则返回false。 允许查询符合指定条件的一组记录 允许查询符合指定条件的第一条记录 触发事件,隐式调用行为和事件管理器中的监听者会被通知 触发事件,隐式调用行为和事件管理器中的监听者会被通知。如果其中一个回调/监听者返回 bool false,此方法将停止执行 返回 DIRTY_STATE_* 常量之一,说明记录是否存在于数据库中 返回验证消息数组 返回与实体实例相关的模型元数据服务 返回 ORM 执行的最新操作类型。返回 OP_* 类常量之一 获取内部数据库连接 返回用于读取数据的 DependencyInjection 连接服务 根据定义的关系返回相关记录 返回表映射所在模式的名称 返回模型中映射的表名 获取内部数据库连接 返回用于写入数据的 DependencyInjection 连接服务 允许获取符合指定条件列的最大值 允许获取符合指定条件列的最小值 为特定模型创建一个查询条件 刷新模型属性,从数据库重新查询记录 插入或更新一个模型实例。成功返回 true,否则返回 false。 设置读写连接服务 使用 DIRTY_STATE_* 常量之一设置对象的脏状态 设置用于读取数据的 DependencyInjection 连接服务 设置记录的快照数据。此方法由内部调用,用于当模型配置了保留快照数据时设置快照数据 设置与模型实例相关联的事务 设置用于写入数据的 DependencyInjection 连接服务 强制跳过当前操作并进入成功状态 允许计算与指定条件匹配的列的总和 更新模型实例。如果该实例在持久化存储中不存在,将抛出异常。成功时返回 true,否则返回 false。 检查验证过程是否生成了任何消息Mvc\ModuleDefinitionInterface
¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Di\DiInterface
-
继承
-
实现
Phalcon\Mvc\ModuleDefinitionInterface
此接口必须由类模块定义实现
方法¶
注册与模块相关的自动加载器 注册与模块相关的服务Mvc\Router¶
-
命名空间
Phalcon\Mvc
-
使用
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
-
继承
AbstractInjectionAware
-
实现
EventsAwareInterface
RouterInterface
Phalcon\Mvc\Router
Phalcon\Mvc\Router 是标准框架路由器。路由是获取 URI 端点(即位于基础 URL 之后的 URI 部分)并将其分解为参数以确定应由哪个模块、控制器及该控制器的哪个动作来接收请求的过程
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();
常量¶
const POSITION_FIRST = 0;
const POSITION_LAST = 1;
const URI_SOURCE_GET_URL = 0;
const URI_SOURCE_SERVER_REQUEST_URI = 1;
属性¶
/**
* @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 int
*/
protected $uriSource;
/**
* @var bool
*/
protected $wasMatched = false;
方法¶
Phalcon\Mvc\Router 构造函数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
);
@parma string namespaceName
设置默认路径数组。如果路由缺少路径,路由器将使用此处定义的路径。此方法不应用于设置404路由 设置事件管理器 设置 URI 源。选择其中一个 URI_SOURCE_* 常量 检查路由器是否匹配任何已定义的路由Mvc\Router\Annotations¶
-
命名空间
Phalcon\Mvc\Router
-
使用
Phalcon\Annotations\Annotation
Phalcon\Di\DiInterface
Phalcon\Mvc\Router
-
继承
Router
-
实现
Phalcon\Mvc\Router\Annotations
一个从类/资源中读取路由注解的路由器
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();
Mvc\Router\Exception¶
-
命名空间
Phalcon\Mvc\Router
-
使用
-
继承
\Exception
-
实现
Phalcon\Mvc\Router\Exception
Phalcon\Mvc\Router 中抛出的异常会使用此类
Mvc\Router\Group¶
-
命名空间
Phalcon\Mvc\Router
-
使用
-
继承
-
实现
GroupInterface
Phalcon\Mvc\Router\Group
用于创建具有通用属性的一组路由的辅助类
$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;
方法¶
Phalcon\Mvc\Router\Group 构造函数public 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
¶
-
命名空间
Phalcon\Mvc\Router
-
使用
-
继承
-
实现
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);
方法¶
public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
Mvc\路由器\路线¶
-
命名空间
Phalcon\Mvc\Router
-
使用
-
继承
-
实现
RouteInterface
Phalcon\Mvc\Router\Route
此类表示添加到路由器的每个路由
属性¶
/**
* @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 = ;
方法¶
Phalcon\Mvc\Router\Route 构造函数 设置在路由匹配时调用的回调。开发人员可以在此处实现任何任意条件。如果回调返回false,则认为路由未匹配$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\路由器\路线接口
¶
-
命名空间
Phalcon\Mvc\Router
-
使用
-
继承
-
实现
Phalcon\Mvc\Router\RouteInterface
Phalcon\Mvc\Router\Route 的接口
方法¶
替换模式中的占位符,返回有效的PCRE正则表达式 添加转换器以对特定参数执行额外转换 返回路由的模式 如果存在,返回主机名限制 返回约束匹配此路由的HTTP方法 返回路由的名称 返回路径 返回路由的模式 返回使用位置作为键和名称作为值的路径 返回路由的ID 重新配置路由,添加新模式和一组路径 重置内部路由ID生成器 为此路由设置主机名限制 设置一组约束该路由匹配的HTTP方法 设置路由的名称 设置一个或多个约束该路由匹配的HTTP方法Mvc\路由器接口
¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Mvc\Router\GroupInterface
Phalcon\Mvc\Router\RouteInterface
-
继承
-
实现
Phalcon\Mvc\Router 的接口
方法¶
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;
Mvc\网址¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Di\AbstractInjectionAware
Phalcon\Di\DiInterface
Phalcon\Mvc\RouterInterface
Phalcon\Mvc\Router\RouteInterface
Phalcon\Mvc\Url\Exception
Phalcon\Mvc\Url\UrlInterface
-
继承
AbstractInjectionAware
-
实现
UrlInterface
此组件有助于生成:URI、URL和路径
// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");
// Generate a URL for a predefined route
echo $url->get(
[
"for" => "blog-post",
"title" => "some-cool-stuff",
"year" => "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",
]
);
Mvc\Url\Exception¶
-
命名空间
Phalcon\Mvc\Url
-
使用
-
继承
\Exception
-
实现
Phalcon\Mvc\Url\Exception
Phalcon\Mvc\Url 中抛出的异常将使用此类
Mvc\Url\UrlInterface
¶
-
命名空间
Phalcon\Mvc\Url
-
使用
-
继承
-
实现
Phalcon\Mvc\Url\UrlInterface 的接口
方法¶
生成一个URL 返回一个基础路径 返回所有生成的URL的前缀。默认为 / 生成一个本地路径 为所有生成的路径设置基础路径 为所有生成的URL设置一个前缀Mvc\View¶
-
命名空间
Phalcon\Mvc
-
使用
Closure
Phalcon\Di\DiInterface
Phalcon\Di\Injectable
Phalcon\Events\EventsAwareInterface
Phalcon\Events\ManagerInterface
Phalcon\Mvc\View\Engine\Php
Phalcon\Mvc\View\Exception
-
继承
Injectable
-
实现
EventsAwareInterface
ViewInterface
Phalcon\Mvc\View
Phalcon\Mvc\View 是用于模型-视图-控制器模式中“视图”部分的类。它的存在是为了帮助保持视图脚本与模型和控制器脚本分离。它提供了一个助手系统、输出过滤器和变量转义功能。
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;
方法¶
Phalcon\Mvc\View 构造函数 魔术方法,用于检索传递给视图的变量 魔术方法,用于检查视图中是否设置了某个变量 魔术方法,用于将变量传递给视图 重置所有“before”模板布局 重置所有“before”模板布局 禁用自动渲染进程 禁用特定级别的渲染 启用自动渲染进程 检查视图是否存在 @deprecated 通过停止输出缓冲结束渲染过程 获取已渲染动作的名称 返回当前渲染视图的路径(或多个路径) 获取基础路径 返回另一个视图阶段的输出 获取已渲染控制器的名称 返回内部事件管理器 返回主视图的名称 获取当前布局子目录 返回主视图的名称 返回传递给视图的参数 渲染一个局部视图// 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
¶
-
命名空间
Phalcon\Mvc\View\Engine
-
使用
Phalcon\Di\DiInterface
Phalcon\Di\Injectable
Phalcon\Mvc\ViewBaseInterface
-
继承
Injectable
-
实现
EngineInterface
所有模板引擎适配器都必须继承此类。这提供了引擎与 Phalcon\Mvc\View 组件之间的基本接口。
属性¶
方法¶
Phalcon\Mvc\View\Engine 构造函数 返回另一个视图阶段的缓存输出 返回与适配器相关的视图组件 渲染另一个视图中的局部内容Mvc\View\Engine\EngineInterface
¶
-
命名空间
Phalcon\Mvc\View\Engine
-
使用
-
继承
-
实现
Phalcon\Mvc\View 引擎适配器的接口
方法¶
返回另一个视图阶段的缓存输出 渲染另一个视图中的局部内容 使用模板引擎渲染视图TODO:将参数更改为数组类型
Mvc\View\Engine\Php¶
-
命名空间
Phalcon\Mvc\View\Engine
-
使用
-
继承
AbstractEngine
-
实现
使用PHP本身作为模板引擎的适配器
方法¶
使用模板引擎渲染视图Mvc\View\Engine\Volt¶
-
命名空间
Phalcon\Mvc\View\Engine
-
使用
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
-
继承
AbstractEngine
-
实现
EventsAwareInterface
专为设计者友好且快速的PHP模板引擎,使用Zephir/C编写
属性¶
/**
* @var Compiler
*/
protected $compiler;
/**
* @var ManagerInterface|null
*/
protected $eventsManager;
/**
* @var array
*/
protected $macros;
/**
* @var array
*/
protected $options;
方法¶
检查宏是否定义并调用它 执行字符串转换 返回 Volt 的编译器 返回内部事件管理器 返回 Volt 的选项 检查needle是否包含在haystack中 长度过滤器。如果传递的是数组/对象则执行 count,否则执行 strlen/mb_strlen 解析预加载元素并设置必要的链接头 @todo 寻找更好的方式来处理这个 使用模板引擎渲染视图 设置事件管理器 设置 Volt 的选项 从字符串/数组/可遍历对象值中提取一个切片 对数组进行排序Mvc\View\Engine\Volt\Compiler¶
-
命名空间
Phalcon\Mvc\View\Engine\Volt
-
使用
Closure
Phalcon\Di\DiInterface
Phalcon\Di\InjectionAwareInterface
Phalcon\Mvc\ViewBaseInterface
-
继承
-
实现
InjectionAwareInterface
该类读取Volt模板并将其编译成纯PHP代码
$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;
方法¶
Phalcon\Mvc\View\Engine\Volt\Compiler 注册一个Volt扩展@var mixed 扩展
在编译器中注册一个新过滤器 在编译器中注册一个新函数 解析属性读取 应用编译器选项将模板编译成文件 此方法不会返回未被编译的模板的编译路径 编译"autoescape"语句并返回PHP代码 编译宏调用 编译"case"/"default"子句并返回PHP代码 编译"do"语句并返回PHP代码 编译 {% raw %}{{
}}
语句并返回 PHP 代码 编译"elseif"语句并返回PHP代码 将模板编译成文件并强制指定目标路径 生成一个 'forelse' 的 PHP 代码 将 "foreach" 中间代码表示编译为普通 PHP 代码 编译一个返回 PHP 代码的 'if' 语句 编译一个返回 PHP 代码的 'include' 语句 编译宏 编译一个返回 PHP 代码的 "return" 语句 @throws \Phalcon\Mvc\View\Engine\Volt\Exception
编译 "set" 语句并返回 PHP 代码。该方法接受由 Volt 解析器生成的数组并创建相应的set
PHP 语句。由于需要对 Volt 解析器有深入了解,在开发过程中这个方法并不特别有用。 <?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]; ?>";
Mvc\View\Engine\Volt\Exception¶
-
命名空间
Phalcon\Mvc\View\Engine\Volt
-
使用
Phalcon\Mvc\View\Exception
-
继承
BaseException
-
实现
Phalcon\Mvc\View 抛出异常的类
属性¶
方法¶
public function __construct( string $message = string, array $statement = [], int $code = int, \Exception $previous = null );
Mvc\View\Exception¶
-
命名空间
Phalcon\Mvc\View
-
使用
-
继承
\Exception
-
实现
Phalcon\Mvc\View\Exception
Phalcon\Mvc\View 抛出异常的类
Mvc\View\Simple¶
-
命名空间
Phalcon\Mvc\View
-
使用
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
-
继承
Injectable
-
实现
EventsAwareInterface
ViewBaseInterface
Phalcon\Mvc\View\Simple
此组件允许渲染没有层级结构的视图
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;
方法¶
Phalcon\Mvc\View\Simple 构造函数 魔术方法,用于检索传递给视图的变量 魔术方法,用于将变量传递给视图 返回当前渲染视图的路径 返回另一个视图阶段的输出 返回内部事件管理器 返回传递给视图的参数 返回之前在视图中设置的参数 获取视图目录 渲染一个局部视图// 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
¶
-
命名空间
Phalcon\Mvc
-
使用
Phalcon\Cache\Adapter\AdapterInterface
-
继承
-
实现
Phalcon\Mvc\ViewInterface
Phalcon\Mvc\View 和 Phalcon\Mvc\View\Simple 的接口
方法¶
返回来自其他视图阶段的缓存输出 返回传递给视图的参数 获取视图目录 渲染一个局部视图 外部设置视图内容 向视图添加参数(setVar 的别名) 向视图添加参数 设置视图目录。根据您的平台,始终添加一个尾随斜杠或反斜杠Mvc\ViewInterface
¶
-
命名空间
Phalcon\Mvc
-
使用
-
继承
ViewBaseInterface
-
实现
Phalcon\Mvc\ViewInterface
Phalcon\Mvc\View 接口