跳转到内容

Phalcon mvc

注意

所有类都以前缀命名Phalcon

Mvc\Application

GitHub上的源码

  • 命名空间

    • 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;

方法

public function handle( string $uri ): ResponseInterface | bool;
处理一个MVC请求

public function sendCookiesOnHandleRequest( bool $sendCookies ): Application;
启用或禁用每次请求处理时发送cookies

public function sendHeadersOnHandleRequest( bool $sendHeaders ): Application;
启用或禁用每次请求处理时发送头信息

public function useImplicitView( bool $implicitView ): Application;
默认情况下。视图会隐式缓冲所有输出,您可以使用此方法完全禁用视图组件

Mvc\Application\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Application
  • 使用

  • 继承

    \Phalcon\Application\Exception

  • 实现

Phalcon\Mvc\Application\Exception

在 Phalcon\Mvc\Application 类中抛出的异常将使用此类

Mvc\ControllerAbstract

GitHub上的源码

  • 命名空间

    • 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",
            ]
        );
    }
}

方法

final public function __construct();
Phalcon\Mvc\Controller 构造函数

Mvc\Controller\BindModelInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Controller
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\Controller\BindModelInterface

Phalcon\Mvc\Controller 的接口

方法

public static function getModelName(): string;
返回与此控制器关联的模型名称

Mvc\ControllerInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\ControllerInterface

控制器处理器的接口

Mvc\Dispatcher

GitHub上的源码

  • 命名空间

    • 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;

方法

public function forward( array $forward ): void;
将执行流程转发到另一个控制器/动作。

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",
    ]
);

public function getActiveController(): ControllerInterface;
返回调度器中的活动控制器

public function getControllerClass(): string;
可能用于分发请求的控制器类名

public function getControllerName(): string;
获取最后调度的控制器名称

public function getLastController(): ControllerInterface;
返回最后分发的控制器

public function getPreviousActionName(): string;
获取上一次调度的动作名称

public function getPreviousControllerName(): string;
获取上一次调度的控制器名称

public function getPreviousNamespaceName(): string;
获取上一次调度的命名空间名称

public function setControllerName( string $controllerName );
设置要调度的控制器名称

public function setControllerSuffix( string $controllerSuffix );
设置默认控制器后缀

public function setDefaultController( string $controllerName );
设置默认控制器名

protected function handleException( \Exception $exception );
处理用户异常

protected function throwDispatchException( string $message, int $exceptionCode = int );
抛出内部异常

Mvc\Dispatcher\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Dispatcher
  • 使用

  • 继承

    \Phalcon\Dispatcher\Exception

  • 实现

Phalcon\Mvc\Dispatcher\Exception

在 Phalcon\Mvc\Dispatcher 中抛出的异常将使用此类

Mvc\DispatcherInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc
  • 使用

    • Phalcon\Dispatcher\DispatcherInterface
  • 继承

    DispatcherInterfaceBase

  • 实现

Phalcon\Mvc\DispatcherInterface

Phalcon\Mvc\Dispatcher 的接口

方法

public function getActiveController(): ControllerInterface;
返回调度器中的活动控制器

public function getControllerName(): string;
获取最后调度的控制器名称

public function getLastController(): ControllerInterface;
返回最后分发的控制器

public function setControllerName( string $controllerName );
设置要调度的控制器名称

public function setControllerSuffix( string $controllerSuffix );
设置默认控制器后缀

public function setDefaultController( string $controllerName );
设置默认控制器名

Mvc\EntityInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\EntityInterface

Phalcon\Mvc\Collection 和 Phalcon\Mvc\Model 的接口

方法

public function readAttribute( string $attribute ): mixed | null;
按属性名读取属性值

public function writeAttribute( string $attribute, mixed $value );
按属性名写入属性值

Mvc\Micro

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( DiInterface $container = null );
Phalcon\Mvc\Micro 构造函数

public function after( mixed $handler ): Micro;
添加一个 'after' 中间件,在执行路由后调用

public function afterBinding( mixed $handler ): Micro;
添加一个 afterBinding 中间件,在模型绑定后调用

public function before( mixed $handler ): Micro;
添加一个 before 中间件,在执行路由前调用

public function delete( string $routePattern, mixed $handler ): RouteInterface;
将路由映射到处理器上,只有当 HTTP 方法为 DELETE 时才匹配

public function error( mixed $handler ): Micro;
设置一个在处理路由时抛出异常时调用的处理器

public function finish( mixed $handler ): Micro;
添加一个 'finish' 中间件,当请求结束时调用

public function get( string $routePattern, mixed $handler ): RouteInterface;
将路由映射到处理器上,只有当 HTTP 方法为 GET 时才匹配

public function getActiveHandler();
返回用于匹配路由的处理器

public function getBoundModels(): array;
返回绑定实例中的绑定模型

public function getEventsManager(): ManagerInterface | null;
返回内部事件管理器

public function getHandlers(): array;
返回附加到应用程序的内部处理器

public function getModelBinder(): BinderInterface | null;
获取模型绑定器

public function getReturnedValue();
返回已执行处理器返回的值

public function getRouter(): RouterInterface;
返回应用程序使用的内部路由器

public function getService( string $serviceName );
从 DI 获取服务

public function getSharedService( string $serviceName );
从 DI 获取共享服务

public function handle( string $uri );
处理整个请求

public function hasService( string $serviceName ): bool;
检查 DI 中是否注册了服务

public function head( string $routePattern, mixed $handler ): RouteInterface;
将路由映射到处理器上,只有当 HTTP 方法为 HEAD 时才匹配

public function map( string $routePattern, mixed $handler ): RouteInterface;
将路由映射到没有 HTTP 方法限制的处理器

public function mount( CollectionInterface $collection ): Micro;
挂载一组处理器

public function notFound( mixed $handler ): Micro;
设置当路由器不匹配任何定义的路由时调用的处理器

public function offsetExists( mixed $offset ): bool;
使用数组语法检查内部服务容器中是否注册了某个服务

public function offsetGet( mixed $offset ): mixed;
允许使用数组语法从内部服务容器中获取共享服务

var_dump(
    $app["request"]
);

public function offsetSet( mixed $offset, mixed $value ): void;
允许使用数组语法在内部服务容器中注册共享服务

   $app["request"] = new \Phalcon\Http\Request();

public function offsetUnset( mixed $offset ): void;
使用数组语法从内部服务容器中移除服务

public function options( string $routePattern, mixed $handler ): RouteInterface;
映射一个路由到仅在 HTTP 方法为 OPTIONS 时才匹配的处理程序

public function patch( string $routePattern, mixed $handler ): RouteInterface;
映射一个路由到仅在 HTTP 方法为 PATCH 时才匹配的处理程序

public function post( string $routePattern, mixed $handler ): RouteInterface;
映射一个路由到仅在 HTTP 方法为 POST 时才匹配的处理程序

public function put( string $routePattern, mixed $handler ): RouteInterface;
映射一个路由到仅在 HTTP 方法为 PUT 时才匹配的处理程序

public function setActiveHandler( mixed $activeHandler );
外部设置与路由匹配时必须调用的处理器

public function setDI( DiInterface $container ): void;
设置DependencyInjector容器

public function setEventsManager( ManagerInterface $eventsManager ): void;
设置事件管理器

public function setModelBinder( BinderInterface $modelBinder, mixed $cache = null ): Micro;
设置模型绑定器

$micro = new Micro($di);

$micro->setModelBinder(
    new Binder(),
    'cache'
);

public function setResponseHandler( mixed $handler ): Micro;
添加一个自定义'response'处理器,代替默认响应处理器调用

public function setService( string $serviceName, mixed $definition, bool $shared = bool ): ServiceInterface;
从DI设置服务

public function stop(): void;
停止中间件执行,防止其他中间件继续执行

Mvc\Micro\Collection

GitHub上的源码

  • 命名空间

    • 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;
映射一个路由到仅在 HTTP 方法为 DELETE 时才匹配的处理程序

public function get( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 GET 时才匹配的处理程序

public function getHandler(): mixed;
返回主处理器

public function getHandlers(): array;
返回已注册的处理器

public function getPrefix(): string;
返回集合前缀(如果有)

public function head( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 HEAD 时才匹配的处理程序

public function isLazy(): bool;
返回主处理器是否需要延迟加载

public function map( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
将路由映射到处理器。

public function mapVia( string $routePattern, callable $handler, mixed $method, string $name = null ): CollectionInterface;
通过方法将路由映射到处理器。

$collection->mapVia(
    "/test",
    "indexAction",
    ["POST", "GET"],
    "test"
);

public function options( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 OPTIONS 时才匹配的处理程序

public function patch( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 PATCH 时才匹配的处理程序

public function post( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 POST 时才匹配的处理程序

public function put( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 PUT 时才匹配的处理程序

public function setHandler( mixed $handler, bool $lazy = bool ): CollectionInterface;
设置主处理器。

public function setLazy( bool $lazy ): CollectionInterface;
设置主处理程序是否必须延迟加载

public function setPrefix( string $prefix ): CollectionInterface;
为集合中添加的所有路由设置一个前缀

protected function addMap( mixed $method, string $routePattern, callable $handler, string $name = null ): void;
向组中添加处理程序的内部函数

Mvc\Micro\CollectionInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Micro
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\Micro\CollectionInterface

Phalcon\Mvc\Micro\Collection 的接口

方法

public function delete( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
将路由映射到处理器上,只有当 HTTP 方法为 DELETE 时才匹配

public function get( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
将路由映射到处理器上,只有当 HTTP 方法为 GET 时才匹配

public function getHandler(): mixed;
返回主处理器

public function getHandlers(): array;
返回已注册的处理器

public function getPrefix(): string;
返回集合前缀(如果有)

public function head( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
将路由映射到处理器上,只有当 HTTP 方法为 HEAD 时才匹配

public function isLazy(): bool;
返回主处理器是否需要延迟加载

public function map( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到处理程序

public function options( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 OPTIONS 时才匹配的处理程序

public function patch( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 PATCH 时才匹配的处理程序

public function post( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 POST 时才匹配的处理程序

public function put( string $routePattern, callable $handler, string $name = null ): CollectionInterface;
映射一个路由到仅在 HTTP 方法为 PUT 时才匹配的处理程序

public function setHandler( mixed $handler, bool $lazy = bool ): CollectionInterface;
设置主处理程序

public function setLazy( bool $lazy ): CollectionInterface;
设置主处理程序是否必须延迟加载

public function setPrefix( string $prefix ): CollectionInterface;
为集合中添加的所有路由设置一个前缀

Mvc\Micro\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Micro
  • 使用

  • 继承

    \Exception

  • 实现

Phalcon\Mvc\Micro 中抛出的异常将使用此类

Mvc\Micro\LazyLoader

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Micro
  • 使用

    • Phalcon\Mvc\Model\BinderInterface
  • 继承

  • 实现

Phalcon\Mvc\Micro\LazyLoader

使用自动加载实现 Mvc\Micro 处理程序的延迟加载

属性

/**
 * @var string
 */
protected $definition;

/**
 * @var object|null
 */
protected $handler;

方法

public function __construct( string $definition );
Phalcon\Mvc\Micro\LazyLoader 构造函数

public function callMethod( string $method, mixed $arguments, BinderInterface $modelBinder = null );
调用 __call 方法

public function getDefinition(): string;
public function getHandler(): object | null;

Mvc\Micro\MiddlewareInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Micro
  • 使用

    • Phalcon\Mvc\Micro
  • 继承

  • 实现

允许在类中实现 Phalcon\Mvc\Micro 中间件

方法

public function call( Micro $application );
调用中间件

Mvc\ModelAbstract

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __call( string $method, array $arguments );
当某个方法未实现时处理方法调用

public static function __callStatic( string $method, array $arguments );
当某个静态方法未实现时处理方法调用

final public function __construct( mixed $data = null, DiInterface $container = null, ManagerInterface $modelsManager = null );
Phalcon\Mvc\Model 构造函数

public function __get( string $property );
使用关联别名作为属性的魔术方法获取相关记录

public function __isset( string $property ): bool;
检查属性是否是有效关联的魔术方法

public function __serialize(): array;
序列化模型

public function __set( string $property, mixed $value );
魔术方法,用于为模型分配值

public function __unserialize( array $data ): void;
反序列化数组到模型

public function addBehavior( BehaviorInterface $behavior ): void;
在模型中设置一个行为

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",
                    ],
                ]
            )
        );
    }
}

public function appendMessage( MessageInterface $message ): ModelInterface;
在验证过程中添加自定义消息

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",
    ]
);

public static function average( array $parameters = [] ): double | ResultsetInterface;
返回满足指定条件的一组行中某列的平均值。

简单查询返回值为浮点数,当使用 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,
    ]
);

public static function cloneResultMapHydrate( array $data, mixed $columnMap, int $hydrationMode );
根据数据和列映射返回一个填充的结果

public static function count( mixed $parameters = null ): int | ResultsetInterface;
统计满足指定条件的记录数量。

返回一个整数用于简单查询,或当使用 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";

public function create(): bool;
插入一个模型实例。如果该实例已存在于持久化存储中,则会抛出异常。成功返回 true,否则返回 false。

// 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();

public function delete(): bool;
删除模型实例。成功时返回true,否则返回false。

$robot = Robots::findFirst("id=100");

$robot->delete();

$robots = Robots::find("type = 'mechanical'");

foreach ($robots as $robot) {
    $robot->delete();
}

public function doSave( CollectionInterface $visited ): bool;
插入或更新模型实例,需要传入一个已访问的对象列表。

public function dump(): array;
返回可用于var_dump()

var_dump(
    $robot->dump()
);

public static function find( mixed $parameters = null );
查询符合指定条件的一组记录

// 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();

public static function findFirst( mixed $parameters = null ): mixed | null;
查询符合指定条件的第一条记录

// 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',
    ]
);

public function fireEvent( string $eventName ): bool;
触发事件,隐式调用行为和事件管理器中的监听者会被通知

public function fireEventCancel( string $eventName ): bool;
触发一个事件,事件管理器中的行为和监听器会被通知。若其中一个回调/监听器返回布尔值 false,则此方法停止执行

public function getChangedFields(): array;
返回变更值列表。

$robots = Robots::findFirst();
print_r($robots->getChangedFields()); // []

$robots->deleted = 'Y';

$robots->getChangedFields();
print_r($robots->getChangedFields()); // ["deleted"]

public function getDirtyState(): int;
返回 DIRTY_STATE_* 常量之一,说明记录是否存在于数据库中

public function getEventsManager(): EventsManagerInterface | null;
返回自定义事件管理器,如果没有则返回 null

public function getMessages( mixed $filter = null ): MessageInterface[];
返回验证消息数组

$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!";
}

public function getModelsManager(): ManagerInterface;
返回与实体实例相关的模型管理器

public function getModelsMetaData(): MetaDataInterface;

public function getOldSnapshotData(): array;
返回内部旧快照数据

public function getOperationMade(): int;
返回 ORM 执行的最新操作类型。返回 OP_* 类常量之一

final public function getReadConnection(): AdapterInterface;
获取用于读取模型数据的连接

final public function getReadConnectionService(): string;
返回用于读取与模型相关的数据的依赖注入连接服务名称

public function getRelated( string $alias, mixed $arguments = null );
根据定义的关系返回相关记录

final public function getSchema(): string | null;
返回映射表所在模式的名称

public function getSnapshotData(): array;
返回内部快照数据

final public function getSource(): string;
返回模型中映射的表名

public function getTransaction(): TransactionInterface | null;

public function getUpdatedFields(): array;
返回一个更新值的列表

$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"]

final public function getWriteConnection(): AdapterInterface;
获取用于向模型写入数据的连接

final public function getWriteConnectionService(): string;
返回用于与模型相关的数据写操作的依赖注入连接服务名称

public function hasChanged( mixed $fieldName = null, bool $allFields = bool ): bool;
检查特定属性是否已更改。这仅在模型保留数据快照时有效

$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

public function hasSnapshotData(): bool;
检查对象是否有内部快照数据

public function hasUpdated( mixed $fieldName = null, bool $allFields = bool ): bool;
检查特定属性是否已被更新。这仅在模型保留数据快照时有效

public function isRelationshipLoaded( string $relationshipAlias ): bool;
检查是否已加载保存的相关记录

仅当记录此前是通过模型且没有任何额外参数的情况下获取时,才返回 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

public function jsonSerialize(): array;
序列化对象以供json_encode使用

echo json_encode($robot);

public static function maximum( mixed $parameters = null ): mixed;
返回符合指定条件的结果集行中某一列的最大值

// 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";

public static function minimum( mixed $parameters = null ): mixed;
返回符合指定条件的结果集行中某一列的最小值

// 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;

public static function query( DiInterface $container = null ): CriteriaInterface;
为特定模型创建一个查询条件

public function readAttribute( string $attribute ): mixed | null;
按属性名读取属性值

echo $robot->readAttribute("name");

public function refresh(): ModelInterface;
刷新模型属性,从数据库重新查询记录

public function save(): bool;
插入或更新一个模型实例。成功返回 true,否则返回 false。

// 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();

public function serialize(): string | null;
序列化对象时忽略连接、服务、关联对象或静态属性

final public function setConnectionService( string $connectionService ): void;
设置依赖注入连接服务名称

public function setDirtyState( int $dirtyState ): ModelInterface | bool;
使用 DIRTY_STATE_* 常量之一设置对象的脏状态

public function setEventsManager( EventsManagerInterface $eventsManager );
设置自定义事件管理器

public function setOldSnapshotData( array $data, mixed $columnMap = null );
设置记录的旧快照数据。此方法由内部调用,用于当模型配置了保留快照数据时设置旧快照数据

final public function setReadConnectionService( string $connectionService ): void;
设置用于读取数据的依赖注入连接服务名称

public function setSnapshotData( array $data, mixed $columnMap = null ): void;
设置记录的快照数据。此方法由内部调用,用于当模型配置了保留快照数据时设置快照数据

public function setTransaction( TransactionInterface $transaction ): ModelInterface;
设置与模型实例相关联的事务

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();
}

final public function setWriteConnectionService( string $connectionService ): void;
设置用于写入数据的依赖注入连接服务名称

public static function setup( array $options ): void;
启用/禁用 ORM 中的选项

public function skipOperation( bool $skip ): void;
强制跳过当前操作并进入成功状态

public static function sum( mixed $parameters = null ): double | ResultsetInterface;
计算符合指定条件的结果集行中某一列的总和

// 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";

public function toArray( mixed $columns = null, mixed $useGetter = bool ): array;
将实例以数组形式表示出来

print_r(
    $robot->toArray()
);

public function unserialize( string $data ): void;
从序列化字符串中反序列化对象

public function update(): bool;
更新模型实例。如果该实例在持久化存储中不存在,则会抛出异常。返回true成功时返回false

<?php

use MyApp\Models\Invoices;

$invoice = Invoices::findFirst('inv_id = 4');

$invoice->inv_total = 120;

$invoice->update();

注意

当通过findFirst()查询记录时,你需要获取完整的对象(没有columns定义),但还需要通过主键进行检索。如果不这样做,ORM 将发出一个INSERT而不是UPDATE.

public function validationHasFailed(): bool;
检查验证过程是否生成了任何消息

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);
    }
}

public function writeAttribute( string $attribute, mixed $value ): void;
按属性名写入属性值

$robot->writeAttribute("name", "Rosey");

protected function allowEmptyStringValues( array $attributes ): void;
设置一个属性列表,这些属性需从生成的UPDATE语句中跳过

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->allowEmptyStringValues(
            [
                "name",
            ]
        );
    }
}

protected function belongsTo( mixed $fields, string $referenceModel, mixed $referencedFields, array $options = [] ): Relation;
在两个模型之间建立反向 1-1 或 n-1 关系

class RobotsParts extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->belongsTo(
            "robots_id",
            Robots::class,
            "id"
        );
    }
}

protected function cancelOperation();
取消当前操作

final protected function checkForeignKeysRestrict(): bool;
读取“属于”关系并在插入或更新记录时检查虚拟外键,以验证插入/更新的值是否存在于关联实体中

final protected function checkForeignKeysReverseCascade(): bool;
读取“hasMany”和“hasOne”关系并在删除记录时检查虚拟外键(级联)

final protected function checkForeignKeysReverseRestrict(): bool;
读取“hasMany”和“hasOne”关系并在删除记录时检查虚拟外键(限制)

protected function collectRelatedToSave(): array;
收集先前查询的(属于、一对一和通过一对一)关联记录以及新添加的记录

protected function doLowInsert( MetaDataInterface $metaData, AdapterInterface $connection, mixed $table, mixed $identityField ): bool;
向关系型数据库系统发送预构建的INSERT SQL语句

protected function doLowUpdate( MetaDataInterface $metaData, AdapterInterface $connection, mixed $table ): bool;
向关系型数据库系统发送预构建的UPDATE SQL语句

protected function getRelatedRecords( string $modelName, string $method, array $arguments );
根据方法名返回相关记录定义的关系。如果关系不存在则返回false

protected static function groupResult( string $functionName, string $alias, mixed $parameters = null ): ResultsetInterface;
为聚合生成一个PHQL SELECT语句

protected function has( MetaDataInterface $metaData, AdapterInterface $connection ): bool;
检查当前记录是否已存在

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;
通过中间关系在两个模型之间建立n-n关系

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;
通过中间关系在两个模型之间建立1-1关系

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",
        );
    }
}

protected function keepSnapshots( bool $keepSnapshot ): void;
设置模型是否必须在内存中保留原始记录快照

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->keepSnapshots(true);
    }
}

final protected function possibleSetter( string $property, mixed $value ): bool;
检查并尝试使用可能的setter

protected function postSave( bool $success, bool $exists ): bool;
在保存记录后执行内部事件

protected function postSaveRelatedRecords( AdapterInterface $connection, mixed $related, CollectionInterface $visited ): bool;
保存在has-one/has-many关系中分配的关联记录

protected function preSave( MetaDataInterface $metaData, bool $exists, mixed $identityField ): bool;
在保存记录前执行内部钩子

protected function preSaveRelatedRecords( AdapterInterface $connection, mixed $related, CollectionInterface $visited ): bool;
保存必须在保存主记录之前存储的关联记录

final protected function setSchema( string $schema ): ModelInterface;
设置映射表所在模式的名称

final protected function setSource( string $source ): ModelInterface;
设置模型应映射到的表名

protected function skipAttributes( array $attributes ): void;
设置一个属性列表,这些属性需从生成的INSERT/UPDATE语句中跳过

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->skipAttributes(
            [
                "price",
            ]
        );
    }
}

protected function skipAttributesOnCreate( array $attributes ): void;
设置一个属性列表,这些属性需从生成的INSERT语句中跳过

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->skipAttributesOnCreate(
            [
                "created_at",
            ]
        );
    }
}

protected function skipAttributesOnUpdate( array $attributes ): void;
设置一个属性列表,这些属性需从生成的UPDATE语句中跳过

class Robots extends \Phalcon\Mvc\Model
{
    public function initialize()
    {
        $this->skipAttributesOnUpdate(
            [
                "modified_in",
            ]
        );
    }
}

protected function useDynamicUpdate( bool $dynamicUpdate ): void;
设置模型是否应使用动态更新而非全字段更新

use Phalcon\Mvc\Model;

class Robots extends Model
{
    public function initialize()
    {
        $this->useDynamicUpdate(true);
    }
}

protected function validate( ValidationInterface $validator ): bool;
在每次验证调用时执行验证器

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\BehaviorAbstract

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Phalcon\Mvc\ModelInterface
  • 继承

  • 实现

    • BehaviorInterface

Phalcon\Mvc\Model\Behavior

ORM行为的一个可选基类

属性

/**
 * @var array
 */
protected $options;

方法

public function __construct( array $options = [] );
Phalcon\Mvc\Model\Behavior

public function missingMethod( ModelInterface $model, string $method, array $arguments = [] );
当调用模型上缺失的方法时作为备用方案

public function notify( string $type, ModelInterface $model );
此方法从EventsManager接收通知

protected function getOptions( string $eventName = null );
Returns the behavior options related to an event

protected function mustTakeAction( string $eventName ): bool;
检查行为是否应在某些事件上采取行动。

Mvc\Model\Behavior\SoftDelete

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Behavior
  • 使用

    • Phalcon\Mvc\ModelInterface
    • Phalcon\Mvc\Model\Behavior
    • Phalcon\Mvc\Model\Exception
  • 继承

    Behavior

  • 实现

Phalcon\Mvc\Model\Behavior\SoftDelete

不是永久删除记录,而是标记记录为已删除,改变标志列的值

方法

public function notify( string $type, ModelInterface $model );
监听来自模型管理器的通知

Mvc\Model\Behavior\Timestampable

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Behavior
  • 使用

    • Closure
    • Phalcon\Mvc\ModelInterface
    • Phalcon\Mvc\Model\Behavior
    • Phalcon\Mvc\Model\Exception
  • 继承

    Behavior

  • 实现

Phalcon\Mvc\Model\Behavior\Timestampable

允许自动更新模型的属性,在记录创建或更新时保存日期时间

方法

public function notify( string $type, ModelInterface $model );
监听来自模型管理器的通知

Mvc\Model\BehaviorInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Phalcon\Mvc\ModelInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\BehaviorInterface

Phalcon\Mvc\Model\Behavior的接口

方法

public function missingMethod( ModelInterface $model, string $method, array $arguments = [] );
当模型中缺少某个方法时调用该方法

public function notify( string $type, ModelInterface $model );
此方法从EventsManager接收通知

Mvc\Model\Binder

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( AdapterInterface $cache = null );
Phalcon\Mvc\Model\Binder构造函数

public function bindToHandler( object $handler, array $params, string $cacheKey, string $methodName = null ): array;
将模型正确地绑定到参数中

public function getBoundModels(): array;
返回活动的绑定模型

public function getCache(): AdapterInterface;
设置缓存实例

public function getOriginalValues(): array;
返回原始值数组

public function setCache( AdapterInterface $cache ): BinderInterface;
获取缓存实例

protected function findBoundModel( mixed $paramValue, string $className ): mixed | bool;
通过参数值查找模型

protected function getParamsFromCache( string $cacheKey ): array | null;
通过键获取缓存中的参数类

protected function getParamsFromReflection( object $handler, array $params, string $cacheKey, string $methodName ): array;
使用反射获取处理器所需的修改后的参数

Mvc\Model\Binder\BindableInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Binder
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\Model\Binder\BindableInterface

可绑定类的接口

方法

public function getModelName(): string | array;
返回与此类关联的模型名称或模型名称及参数键

Mvc\Model\BinderInterfaceInterface

GitHub上的源码

  • 命名空间

    • 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;
将模型正确地绑定到参数中

public function getBoundModels(): array;
获取活动的绑定模型

public function getCache(): AdapterInterface;
获取缓存实例

public function setCache( AdapterInterface $cache ): BinderInterface;
设置缓存实例

Mvc\Model\Criteria

GitHub上的源码

  • 命名空间

    • 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;
使用AND操作符向当前条件中追加一个条件

public function betweenWhere( string $expr, mixed $minimum, mixed $maximum ): CriteriaInterface;
将 BETWEEN 条件追加到当前条件

$criteria->betweenWhere("price", 100.25, 200.50);

public function bind( array $bindParams, bool $merge = bool ): CriteriaInterface;
在条件中设置绑定参数。此方法将替换之前设置的所有绑定参数

public function bindTypes( array $bindTypes ): CriteriaInterface;
在条件中设置绑定类型。此方法将替换之前设置的所有绑定参数

public function cache( array $cache ): CriteriaInterface;
在条件中设置缓存选项。此方法将替换之前设置的所有缓存选项

public function columns( mixed $columns ): 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",
    ]
);

public function conditions( string $conditions ): CriteriaInterface;
将conditions参数添加到条件中

public function createBuilder(): BuilderInterface;
<?php

$invoices = Invoices::query() ->where("inv_cst_id = :customerId:") ->bind(["customerId" => 1]) ->createBuilder();

$invoices = Invoices::query() ->where("inv_cst_id = :customerId:") ->bind(["customerId" => 1]) ->createBuilder();

```php
public function distinct( mixed $distinct ): CriteriaInterface;
设置 SELECT DISTINCT / SELECT ALL 标志

public function execute(): ResultsetInterface;
使用通过条件构建的参数执行find操作

public function forUpdate( bool $forUpdate = bool ): CriteriaInterface;
添加"for_update"参数到查询条件

public static function fromInput( DiInterface $container, string $modelName, array $data, string $operator = string ): CriteriaInterface;
根据输入数组如$_POST构建一个Phalcon\Mvc\Model\Criteria

public function getColumns(): string | array | null;
返回要查询的列

public function getConditions(): string | null;
返回条件中的conditions参数

public function getDI(): DiInterface;
返回DependencyInjector容器

public function getGroupBy();
返回条件中的group子句

public function getHaving();
返回条件中的having子句

public function getLimit(): int | array | null;
返回条件中的limit参数,这将会是

  • 如果仅设置了'limit'而没有设置'offset'则为整数
  • 如果设置了offset和limit,则为包含'number'和'offset'键的数组
  • 如果未设置limit,则为NULL

public function getModelName(): string;
返回将在其上应用条件的内部模型名称

public function getOrderBy(): string | null;
返回查询条件中的order子句

public function getParams(): array;
返回条件中定义的所有参数

public function getWhere(): string | null;
返回条件中的conditions参数

public function groupBy( mixed $group ): CriteriaInterface;
将group-by子句添加到条件中

public function having( mixed $having ): CriteriaInterface;
将having子句添加到条件中

public function inWhere( string $expr, array $values ): CriteriaInterface;
将 IN 条件追加到当前条件

$criteria->inWhere("id", [1, 2, 3]);

public function innerJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
向查询添加 INNER JOIN

<?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;
向查询添加 INNER JOIN

<?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;
向查询添加 LEFT JOIN

<?php

$criteria->leftJoin(
    Invoices::class,
    "i.inv_cst_id = Customers.cst_id",
    "i"
);

public function limit( int $limit, int $offset = int ): CriteriaInterface;
将limit参数添加到条件中

$criteria->limit(100);
$criteria->limit(100, 200);
$criteria->limit("100", "200");

public function notBetweenWhere( string $expr, mixed $minimum, mixed $maximum ): CriteriaInterface;
向当前条件追加一个 NOT BETWEEN 条件

$criteria->notBetweenWhere("price", 100.25, 200.50);

public function notInWhere( string $expr, array $values ): CriteriaInterface;
向当前条件追加一个 NOT IN 条件

$criteria->notInWhere("id", [1, 2, 3]);

public function orWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
使用 OR 运算符向当前条件追加一个条件

public function orderBy( string $orderColumns ): CriteriaInterface;
将order-by子句添加到条件中

public function rightJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
向查询添加 RIGHT JOIN

<?php

$criteria->rightJoin(
    Invoices::class,
    "i.inv_cst_id = Customers.cst_id",
    "i"
);

public function setDI( DiInterface $container ): void;
设置DependencyInjector容器

public function setModelName( string $modelName ): CriteriaInterface;
设置将在其上执行查询的模型

public function sharedLock( bool $sharedLock = bool ): CriteriaInterface;
将"shared_lock"参数添加到条件中

public function where( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
在条件中设置conditions参数

Mvc\Model\CriteriaInterfaceInterface

GitHub上的源码

  • 命名空间

    • 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;
使用AND操作符向当前条件中追加一个条件

public function betweenWhere( string $expr, mixed $minimum, mixed $maximum ): CriteriaInterface;
将 BETWEEN 条件追加到当前条件

$criteria->betweenWhere("price", 100.25, 200.50);

public function bind( array $bindParams ): CriteriaInterface;
在条件中设置绑定参数。此方法将替换之前设置的所有绑定参数

public function bindTypes( array $bindTypes ): CriteriaInterface;
在条件中设置绑定类型。此方法将替换之前设置的所有绑定参数

public function cache( array $cache ): CriteriaInterface;
在条件中设置缓存选项。此方法将替换之前设置的所有缓存选项

public function conditions( string $conditions ): CriteriaInterface;
将conditions参数添加到条件中

public function distinct( mixed $distinct ): CriteriaInterface;
设置 SELECT DISTINCT / SELECT ALL 标志

public function execute(): ResultsetInterface;
使用通过条件构建的参数执行find操作

public function forUpdate( bool $forUpdate = bool ): CriteriaInterface;
将"for_update"参数设置到条件中

public function getColumns(): string | array | null;
返回要查询的列

public function getConditions(): string | null;
返回条件中的conditions参数

public function getGroupBy();
返回条件中的group子句

public function getHaving();
返回条件中的having子句

public function getLimit(): int | array | null;
返回条件中的limit参数,这将会是

  • 如果仅设置了'limit'而没有设置'offset'则为整数
  • 如果设置了offset和limit,则为包含'number'和'offset'键的数组
  • 如果未设置limit,则为NULL

public function getModelName(): string;
返回将在其上应用条件的内部模型名称

public function getOrderBy(): string | null;
返回条件中的order参数

public function getParams(): array;
返回条件中定义的所有参数

public function getWhere(): string | null;
返回条件中的conditions参数

public function groupBy( mixed $group ): CriteriaInterface;
将group-by子句添加到条件中

public function having( mixed $having ): CriteriaInterface;
将having子句添加到条件中

public function inWhere( string $expr, array $values ): CriteriaInterface;
将 IN 条件追加到当前条件

$criteria->inWhere("id", [1, 2, 3]);

public function innerJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
向查询添加 INNER JOIN

$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;
向查询添加 LEFT JOIN

$criteria->leftJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);

public function limit( int $limit, int $offset = int ): CriteriaInterface;
将limit参数设置到条件中

public function notBetweenWhere( string $expr, mixed $minimum, mixed $maximum ): CriteriaInterface;
向当前条件追加一个 NOT BETWEEN 条件

$criteria->notBetweenWhere("price", 100.25, 200.50);

public function notInWhere( string $expr, array $values ): CriteriaInterface;
向当前条件追加一个 NOT IN 条件

$criteria->notInWhere("id", [1, 2, 3]);

public function orWhere( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
使用 OR 运算符向当前条件追加一个条件

public function orderBy( string $orderColumns ): CriteriaInterface;
将order-by参数添加到条件中

public function rightJoin( string $model, mixed $conditions = null, mixed $alias = null ): CriteriaInterface;
向查询添加 RIGHT JOIN

$criteria->rightJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);

public function setModelName( string $modelName ): CriteriaInterface;
设置将在其上执行查询的模型

public function sharedLock( bool $sharedLock = bool ): CriteriaInterface;
将"shared_lock"参数设置到条件中

public function where( string $conditions, mixed $bindParams = null, mixed $bindTypes = null ): CriteriaInterface;
在条件中设置conditions参数

Mvc\Model\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

  • 继承

    \Exception

  • 实现

Phalcon\Mvc\Model\Exception

抛出在Phalcon\Mvc\Model*类中的异常将使用此类

Mvc\Model\Manager

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __destruct();
销毁当前PHQL缓存

public function addBehavior( ModelInterface $model, BehaviorInterface $behavior ): void;
Binds a behavior to a model

public function addBelongsTo( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
建立两个模型之间反向的一对多关系

public function addHasMany( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
Setup a relation 1-n between two models

public function addHasManyToMany( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
Setups a relation n-m between two models

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 clearReusableObjects(): void;
清除内部可重用列表

public function createBuilder( mixed $params = null ): BuilderInterface;
Creates a Phalcon\Mvc\Model\Query\Builder

public function createQuery( string $phql ): QueryInterface;
Creates a Phalcon\Mvc\Model\Query without execute it

public function executeQuery( string $phql, mixed $placeholders = null, mixed $types = null ): mixed;
Creates a Phalcon\Mvc\Model\Query and execute it

$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 existsBelongsTo( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型有belongsTo关系 @deprecated

public function existsHasMany( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型有hasMany关系 @deprecated

public function existsHasManyToMany( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型有hasManyToMany关系 @deprecated

public function existsHasOne( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型有hasOne关系 @deprecated

public function existsHasOneThrough( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型有hasOneThrough关系 @deprecated

public function getBelongsTo( ModelInterface $model ): RelationInterface[] | array;
获取模型中定义的所有belongsTo关系

$relations = $modelsManager->getBelongsTo(
    new Robots()
);

public function getBelongsToRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
Gets belongsTo related records from a model

public function getBuilder(): BuilderInterface | null;
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null

public function getConnectionService( ModelInterface $model, array $connectionServices ): string;
返回用于读取或写入与模型相关的数据的连接服务名称,具体取决于连接服务

public function getCustomEventsManager( ModelInterface $model ): EventsManagerInterface | null;
返回与模型相关的自定义事件管理器,如果没有相关事件管理器则返回null

public function getDI(): DiInterface;
返回DependencyInjector容器

public function getEventsManager(): EventsManagerInterface | null;
返回内部事件管理器

public function getHasMany( ModelInterface $model ): RelationInterface[] | array;
Gets hasMany relations defined on a model

public function getHasManyRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
Gets hasMany related records from a model

public function getHasManyToMany( ModelInterface $model ): RelationInterface[] | array;
Gets hasManyToMany relations defined on a model

public function getHasOne( ModelInterface $model ): array;
Gets hasOne relations defined on a model

public function getHasOneAndHasMany( ModelInterface $model ): RelationInterface[];
Gets hasOne relations defined on a model

public function getHasOneRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ModelInterface | bool;
Gets belongsTo related records from a model

public function getHasOneThrough( ModelInterface $model ): RelationInterface[] | array;
Gets hasOneThrough relations defined on a model

public function getLastInitialized(): ModelInterface;
Get last initialized model

public function getLastQuery(): QueryInterface;
Returns the last query created or executed in the models manager

public function getModelPrefix(): string;
返回所有模型源的前缀。

public function getModelSchema( ModelInterface $model ): string | null;
Returns the mapped schema for a model

public function getModelSource( ModelInterface $model ): string;
Returns the mapped source for a model

public function getReadConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to read data related to a model

public function getReadConnectionService( ModelInterface $model ): string;
Returns the connection service name used to read data related to a model

public function getRelationByAlias( string $modelName, string $alias ): RelationInterface | bool;
Returns a relation by its alias

public function getRelationRecords( RelationInterface $relation, ModelInterface $record, mixed $parameters = null, string $method = null );
Helper method to query records based on a relation definition

public function getRelations( string $modelName ): RelationInterface[];
Query all the relationships defined on a model

public function getRelationsBetween( string $first, string $second ): RelationInterface[] | bool;
查询两个模型之间定义的第一个关系

public function getReusableRecords( string $modelName, string $key );
从内部列表返回一个可重用对象

public function getWriteConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to write data related to a model

public function getWriteConnectionService( ModelInterface $model ): string;
Returns the connection service name used to write data related to a model

public function hasBelongsTo( string $modelName, string $modelRelation ): bool;
Checks whether a model has a belongsTo relation with another model

public function hasHasMany( string $modelName, string $modelRelation ): bool;
Checks whether a model has a hasMany relation with another model

public function hasHasManyToMany( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型具有多对多关系(hasManyToMany)。

public function hasHasOne( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型具有一对一关系(hasOne)。

public function hasHasOneThrough( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型具有一对一经过中间表的关系(hasOneThrough)。

public function initialize( ModelInterface $model ): bool;
在模型管理器中初始化一个模型。

public function isInitialized( string $className ): bool;
Check whether a model is already initialized

public function isKeepingSnapshots( ModelInterface $model ): bool;
检查模型是否为查询的记录保留快照。

public function isUsingDynamicUpdate( ModelInterface $model ): bool;
检查模型是否使用动态更新而不是全字段更新。

final public function isVisibleModelProperty( ModelInterface $model, string $property ): bool;
检查模型属性是否被声明为公共(public)。

$isPublic = $manager->isVisibleModelProperty(
    new Robots(),
    "name"
);

public function keepSnapshots( ModelInterface $model, bool $keepSnapshots ): void;
设置模型是否必须保留快照。

public function load( string $modelName ): ModelInterface;
加载模型,如果不存在则抛出异常。

public function missingMethod( ModelInterface $model, string $eventName, mixed $data );
Dispatch an event to the listeners and behaviors This method expects that the endpoint listeners/behaviors returns true meaning that a least one was implemented

public function notifyEvent( string $eventName, ModelInterface $model );
Receives events generated in the models and dispatches them to an events-manager if available. Notify the behaviors that are listening in the model

public function setConnectionService( ModelInterface $model, string $connectionService ): void;
为模型设置写入和读取连接服务。

public function setCustomEventsManager( ModelInterface $model, EventsManagerInterface $eventsManager ): void;
Sets a custom events manager for a specific model

public function setDI( DiInterface $container ): void;
设置DependencyInjector容器

public function setEventsManager( EventsManagerInterface $eventsManager ): void;
Sets a global events manager

public function setModelPrefix( string $prefix ): void;
Sets the prefix for all model sources.

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

public function setModelSchema( ModelInterface $model, string $schema ): void;
为模型设置映射的数据库模式。

public function setModelSource( ModelInterface $model, string $source ): void;
为模型设置映射的数据源。

public function setReadConnectionService( ModelInterface $model, string $connectionService ): void;
为模型设置读取连接服务。

public function setReusableRecords( string $modelName, string $key, mixed $records ): void;
Stores a reusable record in the internal list

public function setWriteConnectionService( ModelInterface $model, string $connectionService ): void;
为模型设置写入连接服务。

public function useDynamicUpdate( ModelInterface $model, bool $dynamicUpdate ): void;
设置模型是否应使用动态更新而非全字段更新

protected function getConnection( ModelInterface $model, array $connectionServices ): AdapterInterface;
Returns the connection to read or write data related to a model depending on the connection services.

final protected function mergeFindParameters( mixed $findParamsOne, mixed $findParamsTwo ): array;
Merge two arrays of find parameters

Mvc\Model\ManagerInterface Interface

GitHub上的源码

  • 命名空间

    • 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

方法

public function addBehavior( ModelInterface $model, BehaviorInterface $behavior ): void;
Binds a behavior to a model

public function addBelongsTo( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
Setup a relation reverse 1-1 between two models

public function addHasMany( ModelInterface $model, mixed $fields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
Setup a relation 1-n between two models

public function addHasManyToMany( ModelInterface $model, mixed $fields, string $intermediateModel, mixed $intermediateFields, mixed $intermediateReferencedFields, string $referencedModel, mixed $referencedFields, array $options = [] ): RelationInterface;
Setups a relation n-m between two models

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;
Setups a 1-1 relation between two models using an intermediate table

public function createBuilder( mixed $params = null ): BuilderInterface;
Creates a Phalcon\Mvc\Model\Query\Builder

public function createQuery( string $phql ): QueryInterface;
Creates a Phalcon\Mvc\Model\Query without execute it

public function executeQuery( string $phql, mixed $placeholders = null, mixed $types = null ): mixed;
Creates a Phalcon\Mvc\Model\Query and execute it

public function getBelongsTo( ModelInterface $model ): RelationInterface[] | array;
Gets belongsTo relations defined on a model

public function getBelongsToRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
Gets belongsTo related records from a model

public function getBuilder(): BuilderInterface | null;
Returns the newly created Phalcon\Mvc\Model\Query\Builder or null

public function getHasMany( ModelInterface $model ): RelationInterface[] | array;
Gets hasMany relations defined on a model

public function getHasManyRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ResultsetInterface | bool;
Gets hasMany related records from a model

public function getHasManyToMany( ModelInterface $model ): RelationInterface[] | array;
Gets hasManyToMany relations defined on a model

public function getHasOne( ModelInterface $model ): RelationInterface[] | array;
Gets hasOne relations defined on a model

public function getHasOneAndHasMany( ModelInterface $model ): RelationInterface[];
Gets hasOne relations defined on a model

public function getHasOneRecords( string $modelName, string $modelRelation, ModelInterface $record, mixed $parameters = null, string $method = null ): ModelInterface | bool;
Gets hasOne related records from a model

public function getHasOneThrough( ModelInterface $model ): RelationInterface[] | array;
Gets hasOneThrough relations defined on a model

public function getLastInitialized(): ModelInterface;
Get last initialized model

public function getLastQuery(): QueryInterface;
Returns the last query created or executed in the models manager

public function getModelSchema( ModelInterface $model ): string | null;
Returns the mapped schema for a model

public function getModelSource( ModelInterface $model ): string;
Returns the mapped source for a model

public function getReadConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to read data related to a model

public function getReadConnectionService( ModelInterface $model ): string;
Returns the connection service name used to read data related to a model

public function getRelationByAlias( string $modelName, string $alias ): RelationInterface | bool;
Returns a relation by its alias

public function getRelationRecords( RelationInterface $relation, ModelInterface $record, mixed $parameters = null, string $method = null );
Helper method to query records based on a relation definition

public function getRelations( string $modelName ): RelationInterface[];
Query all the relationships defined on a model

public function getRelationsBetween( string $first, string $second ): RelationInterface[] | bool;
Query the relations between two models

public function getWriteConnection( ModelInterface $model ): AdapterInterface;
Returns the connection to write data related to a model

public function getWriteConnectionService( ModelInterface $model ): string;
Returns the connection service name used to write data related to a model

public function hasBelongsTo( string $modelName, string $modelRelation ): bool;
Checks whether a model has a belongsTo relation with another model

public function hasHasMany( string $modelName, string $modelRelation ): bool;
Checks whether a model has a hasMany relation with another model

public function hasHasManyToMany( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型具有多对多关系(hasManyToMany)。

public function hasHasOne( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型具有一对一关系(hasOne)。

public function hasHasOneThrough( string $modelName, string $modelRelation ): bool;
检查模型是否与另一个模型具有一对一经过中间表的关系(hasOneThrough)。

public function initialize( ModelInterface $model );
在模型管理器中初始化一个模型。

public function isInitialized( string $className ): bool;
检查模型是否已经初始化。

public function isKeepingSnapshots( ModelInterface $model ): bool;
检查模型是否为查询的记录保留快照。

public function isUsingDynamicUpdate( ModelInterface $model ): bool;
检查模型是否使用动态更新而不是全字段更新。

public function isVisibleModelProperty( ModelInterface $model, string $property ): bool;
检查模型属性是否被声明为公共(public)。

$isPublic = $manager->isVisibleModelProperty(
    new Robots(),
    "name"
);

public function keepSnapshots( ModelInterface $model, bool $keepSnapshots ): void;
设置模型是否必须保留快照。

public function load( string $modelName ): ModelInterface;
加载模型,如果不存在则抛出异常。

public function missingMethod( ModelInterface $model, string $eventName, mixed $data );
向监听器和行为派发事件。此方法期望端点 listeners/behaviors 返回 true,表示至少有一个已实现。

public function notifyEvent( string $eventName, ModelInterface $model );
接收在模型中生成的事件,并将其派发到事件管理器(如果有)。通知正在监听模型的行为。

public function setConnectionService( ModelInterface $model, string $connectionService ): void;
为模型设置写入和读取连接服务。

public function setModelSchema( ModelInterface $model, string $schema ): void;
为模型设置映射的数据库模式。

public function setModelSource( ModelInterface $model, string $source ): void;
为模型设置映射的数据源。

public function setReadConnectionService( ModelInterface $model, string $connectionService ): void;
为模型设置读取连接服务。

public function setWriteConnectionService( ModelInterface $model, string $connectionService );
为模型设置写入连接服务。

public function useDynamicUpdate( ModelInterface $model, bool $dynamicUpdate ): void;
设置模型是否应使用动态更新而非全字段更新

Mvc\Model\MetaDataAbstract

GitHub上的源码

  • 命名空间

    • 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;

方法

public function getAdapter(): CacheAdapterInterface | null;
返回内部缓存适配器。

public function getAttributes( ModelInterface $model ): array;
返回表属性名(字段)

print_r(
    $metaData->getAttributes(
        new Robots()
    )
);

public function getAutomaticCreateAttributes( ModelInterface $model ): array;
返回必须忽略的 INSERT SQL 生成属性

print_r(
    $metaData->getAutomaticCreateAttributes(
        new Robots()
    )
);

public function getAutomaticUpdateAttributes( ModelInterface $model ): array;
返回必须忽略的 UPDATE SQL 生成属性

print_r(
    $metaData->getAutomaticUpdateAttributes(
        new Robots()
    )
);

public function getBindTypes( ModelInterface $model ): array;
返回属性及其绑定数据类型

print_r(
    $metaData->getBindTypes(
        new Robots()
    )
);

public function getColumnMap( ModelInterface $model ): array | null;
如果有的话返回列映射

print_r(
    $metaData->getColumnMap(
        new Robots()
    )
);

public function getDI(): DiInterface;
返回DependencyInjector容器

public function getDataTypes( ModelInterface $model ): array;
返回属性及其数据类型

print_r(
    $metaData->getDataTypes(
        new Robots()
    )
);

public function getDataTypesNumeric( ModelInterface $model ): array;
返回类型为数值的属性

print_r(
    $metaData->getDataTypesNumeric(
        new Robots()
    )
);

public function getDefaultValues( ModelInterface $model ): array;
返回具有默认值的属性及其默认值

print_r(
    $metaData->getDefaultValues(
        new Robots()
    )
);

public function getEmptyStringAttributes( ModelInterface $model ): array;
返回允许空字符串的属性

print_r(
    $metaData->getEmptyStringAttributes(
        new Robots()
    )
);

public function getIdentityField( ModelInterface $model ): string | null;
返回标识字段的名称(如果存在一个)

print_r(
    $metaData->getIdentityField(
        new Robots()
    )
);

public function getNonPrimaryKeyAttributes( ModelInterface $model ): array;
返回不属于主键的字段数组

print_r(
    $metaData->getNonPrimaryKeyAttributes(
        new Robots()
    )
);

public function getNotNullAttributes( ModelInterface $model ): array;
返回非空属性的数组

print_r(
    $metaData->getNotNullAttributes(
        new Robots()
    )
);

public function getPrimaryKeyAttributes( ModelInterface $model ): array;
返回属于主键的字段数组

print_r(
    $metaData->getPrimaryKeyAttributes(
        new Robots()
    )
);

public function getReverseColumnMap( ModelInterface $model ): array | null;
如果有的话返回反向列映射

print_r(
    $metaData->getReverseColumnMap(
        new Robots()
    )
);

public function getStrategy(): StrategyInterface;
返回获取元数据的策略

public function hasAttribute( ModelInterface $model, string $attribute ): bool;
检查模型是否具有某个属性

var_dump(
    $metaData->hasAttribute(
        new Robots(),
        "name"
    )
);

public function isEmpty(): bool;
检查内部元数据容器是否为空

var_dump(
    $metaData->isEmpty()
);

public function read( string $key ): array | null;
从适配器读取元数据

final public function readColumnMap( ModelInterface $model ): array | null;
读取特定模型的有序/反向列映射

print_r(
    $metaData->readColumnMap(
        new Robots()
    )
);

final public function readColumnMapIndex( ModelInterface $model, int $index ): array | null;
使用 MODEL_* 常量读取特定模型的列映射信息

print_r(
    $metaData->readColumnMapIndex(
        new Robots(),
        MetaData::MODELS_REVERSE_COLUMN_MAP
    )
);

final public function readMetaData( ModelInterface $model ): array | null;
读取特定模型的完整元数据

print_r(
    $metaData->readMetaData(
        new Robots()
    )
);

final public function readMetaDataIndex( ModelInterface $model, int $index ): array | null;
读取特定模型的元数据

print_r(
    $metaData->readMetaDataIndex(
        new Robots(),
        0
    )
);

public function reset(): void;
重置内部元数据以便重新生成它

$metaData->reset();

public function setAutomaticCreateAttributes( ModelInterface $model, array $attributes ): void;
设置必须从 INSERT SQL 生成中忽略的属性

$metaData->setAutomaticCreateAttributes(
    new Robots(),
    [
        "created_at" => true,
    ]
);

public function setAutomaticUpdateAttributes( ModelInterface $model, array $attributes ): void;
设置必须从 UPDATE SQL 生成中忽略的属性

$metaData->setAutomaticUpdateAttributes(
    new Robots(),
    [
        "modified_at" => true,
    ]
);

public function setDI( DiInterface $container ): void;
设置DependencyInjector容器

public function setEmptyStringAttributes( ModelInterface $model, array $attributes ): void;
设置允许空字符串值的属性

$metaData->setEmptyStringAttributes(
    new Robots(),
    [
        "name" => true,
    ]
);

public function setStrategy( StrategyInterface $strategy ): void;
设置元数据提取策略

public function write( string $key, array $data ): void;
将元数据写入适配器

final public function writeMetaDataIndex( ModelInterface $model, int $index, mixed $data ): void;
使用 MODEL_* 常量为特定模型写入元数据

print_r(
    $metaData->writeColumnMapIndex(
        new Robots(),
        MetaData::MODELS_REVERSE_COLUMN_MAP,
        [
            "leName" => "name",
        ]
    )
);

protected function getArrVal( array $collection, mixed $index, mixed $defaultValue = null ): mixed;
@todo 当我们获得特性时,删除这个

final protected function initialize( ModelInterface $model, mixed $key, mixed $table, mixed $schema );
为兼容性初始化旧行为

final protected function initializeColumnMap( ModelInterface $model, mixed $key ): bool;
为特定表初始化 ColumnMap

final protected function initializeMetaData( ModelInterface $model, mixed $key ): bool;
获取元数据是一项代价昂贵的数据库操作,我们当然不想在每次运行查询时都执行它。但是我们可以使用许多可用的适配器之一来缓存元数据。

Mvc\Model\MetaData\Apcu

GitHub上的源码

  • 命名空间

    • 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,
    ]
);

方法

public function __construct( AdapterFactory $factory, array $options = null );
Phalcon\Mvc\Model\MetaData\Apcu 构造函数

Mvc\Model\MetaData\Libmemcached

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\MetaData
  • 使用

    • Phalcon\Cache\AdapterFactory
    • Phalcon\Mvc\Model\Exception
    • Phalcon\Mvc\Model\MetaData
  • 继承

    MetaData

  • 实现

Phalcon\Mvc\Model\MetaData\Libmemcached

将模型元数据存储在 Memcache 中。

默认元数据存储 48 小时(172800 秒)

方法

public function __construct( AdapterFactory $factory, array $options = [] );
Phalcon\Mvc\Model\MetaData\Libmemcached 构造函数

public function reset(): void;
清空 Memcache 数据并重置内部元数据以便重新生成

Mvc\Model\MetaData\Memory

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\MetaData
  • 使用

    • Phalcon\Mvc\Model\Exception
    • Phalcon\Mvc\Model\MetaData
  • 继承

    MetaData

  • 实现

Phalcon\Mvc\Model\MetaData\Memory

将模型元数据存储在内存中。请求结束后数据将被清除

方法

public function __construct( mixed $options = null );
Phalcon\Mvc\Model\MetaData\Memory 构造函数

public function read( string $key ): array | null;
从临时内存读取元数据

public function write( string $key, array $data ): void;
将元数据写入临时内存

Mvc\Model\MetaData\Redis

GitHub上的源码

  • 命名空间

    • 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,
    ]
);

方法

public function __construct( AdapterFactory $factory, array $options = [] );
Phalcon\Mvc\Model\MetaData\Redis 构造函数

public function reset(): void;
清空 Redis 数据并重置内部元数据以便重新生成

Mvc\Model\MetaData\Strategy\Annotations

GitHub上的源码

  • 命名空间

    • 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文件。

方法

final public function getColumnMaps( ModelInterface $model, DiInterface $container ): array;
读取模型的列映射,这无法推断

final public function getMetaData( ModelInterface $model, DiInterface $container ): array;
元数据是通过读取数据库信息模式中的列描述来获得的

Mvc\Model\MetaData\Strategy\Introspection

GitHub上的源码

  • 命名空间

    • 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

查询表元数据以检测模型的元数据

方法

final public function getColumnMaps( ModelInterface $model, DiInterface $container ): array;
读取模型的列映射,这无法推断

final public function getMetaData( ModelInterface $model, DiInterface $container ): array;
元数据是通过读取数据库信息模式中的列描述来获得的

Mvc\Model\MetaData\Strategy\StrategyInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\MetaData\Strategy
  • 使用

    • Phalcon\Di\DiInterface
    • Phalcon\Mvc\ModelInterface
  • 继承

  • 实现

该文件是Phalcon框架的一部分。

(c) Phalcon团队team@phalcon.io

有关完整的版权和许可信息,请查看随此源代码分发的LICENSE.txt文件。

方法

public function getColumnMaps( ModelInterface $model, DiInterface $container ): array;
读取模型的列映射,这无法推断

@todo 尚未实现

public function getMetaData( ModelInterface $model, DiInterface $container ): array;
元数据是通过读取数据库信息模式中的列描述来获得的

Mvc\Model\MetaData\Stream

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\MetaData
  • 使用

    • Phalcon\Mvc\Model\Exception
    • Phalcon\Mvc\Model\MetaData
  • 继承

    MetaData

  • 实现

Phalcon\Mvc\Model\MetaData\Stream

将模型元数据存储在 PHP 文件中。

$metaData = new \Phalcon\Mvc\Model\MetaData\Files(
    [
        "metaDataDir" => "app/cache/metadata/",
    ]
);

属性

/**
 * @var string
 */
protected $metaDataDir = ./;

方法

public function __construct( array $options = [] );
Phalcon\Mvc\Model\MetaData\Files 构造函数

public function read( string $key ): array | null;
从文件读取元数据

public function write( string $key, array $data ): void;
将元数据写入文件

Mvc\Model\MetaDataInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Phalcon\Mvc\ModelInterface
    • Phalcon\Mvc\Model\MetaData\Strategy\StrategyInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\MetaDataInterface

Phalcon\Mvc\Model\MetaData 的接口

方法

public function getAttributes( ModelInterface $model ): array;
返回表属性名(字段)

public function getAutomaticCreateAttributes( ModelInterface $model ): array;
返回必须忽略的 INSERT SQL 生成属性

public function getAutomaticUpdateAttributes( ModelInterface $model ): array;
返回必须忽略的 UPDATE SQL 生成属性

public function getBindTypes( ModelInterface $model ): array;
返回属性及其绑定数据类型

public function getColumnMap( ModelInterface $model ): array | null;
如果有的话返回列映射

public function getDataTypes( ModelInterface $model ): array;
返回属性及其数据类型

public function getDataTypesNumeric( ModelInterface $model ): array;
返回类型为数值的属性

public function getDefaultValues( ModelInterface $model ): array;
返回具有默认值的属性及其默认值

public function getEmptyStringAttributes( ModelInterface $model ): array;
返回允许空字符串的属性

public function getIdentityField( ModelInterface $model ): string | null;
返回标识字段的名称(如果存在一个)

public function getNonPrimaryKeyAttributes( ModelInterface $model ): array;
返回不属于主键的字段数组

public function getNotNullAttributes( ModelInterface $model ): array;
返回非空属性的数组

public function getPrimaryKeyAttributes( ModelInterface $model ): array;
返回属于主键的字段数组

public function getReverseColumnMap( ModelInterface $model ): array | null;
如果有的话返回反向列映射

public function getStrategy(): StrategyInterface;
返回获取元数据的策略

public function hasAttribute( ModelInterface $model, string $attribute ): bool;
检查模型是否具有某个属性

public function isEmpty(): bool;
检查内部元数据容器是否为空

public function read( string $key ): array | null;
从适配器读取元数据

public function readColumnMap( ModelInterface $model ): array | null;
读取特定模型的有序/反向列映射

public function readColumnMapIndex( ModelInterface $model, int $index ): array | null;
使用 MODEL_* 常量读取特定模型的列映射信息

public function readMetaData( ModelInterface $model ): array | null;
读取特定模型的元数据

public function readMetaDataIndex( ModelInterface $model, int $index ): array | null;
使用 MODEL_* 常量读取特定模型的元数据

public function reset();
重置内部元数据以便重新生成它

public function setAutomaticCreateAttributes( ModelInterface $model, array $attributes );
设置必须从 INSERT SQL 生成中忽略的属性

public function setAutomaticUpdateAttributes( ModelInterface $model, array $attributes );
设置必须从 UPDATE SQL 生成中忽略的属性

public function setEmptyStringAttributes( ModelInterface $model, array $attributes ): void;
设置允许空字符串值的属性

public function setStrategy( StrategyInterface $strategy );
设置元数据提取策略

public function write( string $key, array $data ): void;
将元数据写入适配器

public function writeMetaDataIndex( ModelInterface $model, int $index, mixed $data );
使用 MODEL_* 常量为特定模型写入元数据

Mvc\Model\Query

GitHub上的源码

  • 命名空间

    • 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();

常量

const TYPE_DELETE = 303;
const TYPE_INSERT = 306;
const TYPE_SELECT = 309;
const TYPE_UPDATE = 300;

属性

/**
 * @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 = [] );
Phalcon\Mvc\Model\Query 构造函数

public function cache( array $cacheOptions ): QueryInterface;
设置查询的缓存参数

public static function clean(): void;
销毁内部 PHQL 缓存

public function execute( array $bindParams = [], array $bindTypes = [] );
执行已解析的 PHQL 语句

public function getBindParams(): array;
返回默认绑定参数

public function getBindTypes(): array;
返回默认绑定类型

public function getCache(): AdapterInterface;
返回当前缓存后端实例

public function getCacheOptions(): array;
返回当前缓存选项

public function getDI(): DiInterface;
返回依赖注入容器

public function getIntermediate(): array;
返回 PHQL 语句的中间表示

public function getSingleResult( array $bindParams = [], array $bindTypes = [] ): ModelInterface;
执行查询并返回第一个结果

public function getSql(): array;
返回由内部 PHQL 生成的 SQL(仅适用于 SELECT 语句)

public function getTransaction(): TransactionInterface | null;

public function getType(): int;
获取执行的 PHQL 语句类型

public function getUniqueRow(): bool;
检查查询是否被设置为只获取结果集中的第一行

public function parse(): array;
解析 Phalcon\Mvc\Model\Query\Lang 生成的中间代码,生成另一个可由 Phalcon\Mvc\Model\Query 执行的中间表示

public function setBindParams( array $bindParams, bool $merge = bool ): QueryInterface;
设置默认绑定参数

public function setBindTypes( array $bindTypes, bool $merge = bool ): QueryInterface;
设置默认绑定参数

public function setDI( DiInterface $container ): void;
设置依赖注入容器

public function setIntermediate( array $intermediate ): QueryInterface;
允许设置要执行的 IR

public function setSharedLock( bool $sharedLock = bool ): QueryInterface;
设置 SHARED LOCK 子句

public function setTransaction( TransactionInterface $transaction ): QueryInterface;
允许在所有查询周围包装事务

public function setType( int $type ): QueryInterface;
设置要执行的 PHQL 语句类型

public function setUniqueRow( bool $uniqueRow ): QueryInterface;
告诉查询是否只应返回结果集中的第一行

final protected function _prepareDelete(): array;
分析 DELETE 中间代码并生成稍后可执行的数组

final protected function _prepareInsert(): array;
分析 INSERT 中间代码并生成稍后可执行的数组

final protected function _prepareSelect( mixed $ast = null, bool $merge = bool ): array;
分析 SELECT 中间代码并生成稍后可执行的数组

final protected function _prepareUpdate(): array;
分析 UPDATE 中间代码并生成稍后可执行的数组

final protected function executeDelete( array $intermediate, array $bindParams, array $bindTypes ): StatusInterface;
执行 DELETE 中间表示并生成一个 Phalcon\Mvc\Model\Query\Status

final protected function executeInsert( array $intermediate, array $bindParams, array $bindTypes ): StatusInterface;
执行 INSERT 中间表示并生成一个 Phalcon\Mvc\Model\Query\Status

final protected function executeSelect( array $intermediate, array $bindParams, array $bindTypes, bool $simulate = bool ): ResultsetInterface | array;
执行 SELECT 中间表示并生成一个 Phalcon\Mvc\Model\Resultset

final protected function executeUpdate( array $intermediate, array $bindParams, array $bindTypes ): StatusInterface;
执行 UPDATE 中间表示并生成一个 Phalcon\Mvc\Model\Query\Status

final protected function getCallArgument( array $argument ): array;
解析单个调用参数中的表达式

final protected function getCaseExpression( array $expr ): array;
解析单个调用参数中的表达式

final protected function getExpression( array $expr, bool $quoting = bool ): array;
将表达式从其中间代码解析为数组

final protected function getFunctionCall( array $expr ): array;
解析单个调用参数中的表达式

final protected function getGroupClause( array $group ): array;
返回用于 SELECT 语句的已处理 GROUP 子句

final protected function getJoin( ManagerInterface $manager, array $join ): array;
解析 JOIN 子句,检查关联模型是否存在

final protected function getJoinType( array $join ): string;
解析 JOIN 类型

final protected function getJoins( array $select ): array;
处理查询中的 JOIN,并返回数据库方言的内部表示

final protected function getLimitClause( array $limitClause ): array;
返回用于 SELECT 语句的已处理 LIMIT 子句

final protected function getMultiJoin( string $joinType, mixed $joinSource, string $modelAlias, string $joinAlias, RelationInterface $relation ): array;
解析涉及多对多关系的 JOIN

final protected function getOrderClause( mixed $order ): array;
返回用于 SELECT 语句的已处理 ORDER 子句

final protected function getQualified( array $expr ): 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;
查询将执行 UPDATE/DELETE 操作的记录

final protected function getSelectColumn( array $column ): array;
将列从中间表示解析为数组,用于判断结果集是简单还是复杂

final protected function getSingleJoin( string $joinType, mixed $joinSource, string $modelAlias, string $joinAlias, RelationInterface $relation ): array;
解析涉及一对一、属于、一对多关系的 JOIN

final protected function getTable( ManagerInterface $manager, array $qualifiedName );
解析 SELECT 语句中的表,检查模型是否存在

protected function getWriteConnection( ModelInterface $model, array $intermediate = null, array $bindParams = [], array $bindTypes = [] ): AdapterInterface;
如果查询对象中没有事务,则从模型获取写入连接

Mvc\Model\Query\Builder

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( mixed $params = null, DiInterface $container = null );
Phalcon\Mvc\Model\Query\Builder 构造函数

public function addFrom( string $model, string $alias = null ): BuilderInterface;
添加一个模型参与查询

// 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;
使用 AND 运算符将条件追加到当前 HAVING 条件子句

$builder->andHaving("SUM(Robots.price) > 0");

$builder->andHaving(
    "SUM(Robots.price) > :sum:",
    [
        "sum" => 100,
    ]
);

public function andWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
使用 AND 运算符将条件追加到当前 WHERE 条件

$builder->andWhere("name = 'Peter'");

$builder->andWhere(
    "name = :name: AND id > :id:",
    [
        "name" => "Peter",
        "id"   => 100,
    ]
);

final public function autoescape( string $identifier ): string;
自动转义标识符,但仅在需要时才进行转义。

public function betweenHaving( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
将 BETWEEN 条件追加到当前 HAVING 条件子句

$builder->betweenHaving("SUM(Robots.price)", 100.25, 200.50);

public function betweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
将 BETWEEN 条件追加到当前 WHERE 条件

$builder->betweenWhere("price", 100.25, 200.50);

public function columns( mixed $columns ): 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",
    ]
);

public function distinct( mixed $distinct ): BuilderInterface;
设置 SELECT DISTINCT / SELECT ALL 标志

$builder->distinct("status");
$builder->distinct(null);

public function forUpdate( bool $forUpdate ): BuilderInterface;
设置 FOR UPDATE 子句

$builder->forUpdate(true);

public function from( mixed $models ): BuilderInterface;
设置参与查询的模型

$builder->from(
    Robots::class
);

$builder->from(
    [
        Robots::class,
        RobotsParts::class,
    ]
);

$builder->from(
    [
        "r"  => Robots::class,
        "rp" => RobotsParts::class,
    ]
);

public function getBindParams(): array;
返回默认绑定参数

public function getBindTypes(): array;
返回默认绑定类型

public function getColumns();
返回要查询的列

public function getDI(): DiInterface;
返回DependencyInjector容器

public function getDistinct(): bool;
返回 SELECT DISTINCT / SELECT ALL 标志

public function getFrom();
返回参与查询的模型

public function getGroupBy(): array;
返回 GROUP BY 子句

public function getHaving(): string;
返回当前 HAVING 子句

public function getJoins(): array;
返回查询的 JOIN 部分

public function getLimit();
返回当前 LIMIT 子句

public function getModels(): string | array | null;
返回查询涉及的模型

public function getOffset(): int;
返回当前 OFFSET 子句

public function getOrderBy();
返回已设置的 ORDER BY 子句

final public function getPhql(): string;
基于构建器参数生成并返回一个 PHQL 语句

public function getQuery(): QueryInterface;
返回构建好的查询

public function getWhere();
返回查询的条件

public function groupBy( mixed $group ): BuilderInterface;
设置 GROUP BY 子句

$builder->groupBy(
    [
        "Robots.name",
    ]
);

public function having( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
设置 HAVING 条件子句

$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;
将 IN 条件追加到当前 HAVING 条件子句

$builder->inHaving("SUM(Robots.price)", [100, 200]);

public function inWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
将 IN 条件追加到当前 WHERE 条件

$builder->inWhere(
    "id",
    [1, 2, 3]
);

public function innerJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
向查询添加 INNER JOIN

// 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;
向查询添加 :type: JOIN(默认类型 - INNER)

// 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;
向查询添加 LEFT JOIN

$builder->leftJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);

public function limit( int $limit, mixed $offset = null ): BuilderInterface;
设置 LIMIT 子句,可选地设置一个偏移量子句

$builder->limit(100);
$builder->limit(100, 20);
$builder->limit("100", "20");

public function notBetweenHaving( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
将 NOT BETWEEN 条件追加到当前 HAVING 条件子句

$builder->notBetweenHaving("SUM(Robots.price)", 100.25, 200.50);

public function notBetweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
将 NOT BETWEEN 条件追加到当前 WHERE 条件

$builder->notBetweenWhere("price", 100.25, 200.50);

public function notInHaving( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
将 NOT IN 条件追加到当前 HAVING 条件子句

$builder->notInHaving("SUM(Robots.price)", [100, 200]);

public function notInWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
将 NOT IN 条件追加到当前 WHERE 条件

$builder->notInWhere("id", [1, 2, 3]);

public function offset( int $offset ): BuilderInterface;
设置 OFFSET 子句

$builder->offset(30);

public function orHaving( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
使用 OR 运算符将条件追加到当前 HAVING 条件子句

$builder->orHaving("SUM(Robots.price) > 0");

$builder->orHaving(
    "SUM(Robots.price) > :sum:",
    [
        "sum" => 100,
    ]
);

public function orWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
使用 OR 运算符向当前条件追加一个条件

$builder->orWhere("name = 'Peter'");

$builder->orWhere(
    "name = :name: AND id > :id:",
    [
        "name" => "Peter",
        "id"   => 100,
    ]
);

public function orderBy( mixed $orderBy ): BuilderInterface;
设置 ORDER BY 条件子句

$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;
向查询添加 RIGHT JOIN

$builder->rightJoin(
    Robots::class,
    "r.id = RobotsParts.robots_id",
    "r"
);

public function setBindParams( array $bindParams, bool $merge = bool ): BuilderInterface;
设置默认绑定参数

public function setBindTypes( array $bindTypes, bool $merge = bool ): BuilderInterface;
设置默认绑定类型

public function setDI( DiInterface $container ): void;
设置DependencyInjector容器

public function where( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
设置查询的 WHERE 条件

$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;
追加一个 BETWEEN 条件

protected function conditionIn( string $clause, string $operator, string $expr, array $values ): BuilderInterface;
追加一个 IN 条件

protected function conditionNotBetween( string $clause, string $operator, string $expr, mixed $minimum, mixed $maximum ): BuilderInterface;
追加一个 NOT BETWEEN 条件

protected function conditionNotIn( string $clause, string $operator, string $expr, array $values ): BuilderInterface;
追加一个 NOT IN 条件

Mvc\Model\Query\BuilderInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Query
  • 使用

    • Phalcon\Mvc\Model\QueryInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\Query\BuilderInterface

Phalcon\Mvc\Model\Query\Builder 的接口

常量

const OPERATOR_AND = and;
const OPERATOR_OR = or;

方法

public function addFrom( string $model, string $alias = null ): BuilderInterface;
添加一个模型参与查询

public function andWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
使用 AND 运算符将条件追加到当前条件

public function betweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
将 BETWEEN 条件追加到当前条件

public function columns( mixed $columns ): 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 distinct( mixed $distinct ): BuilderInterface;
设置 SELECT DISTINCT / SELECT ALL 标志

$builder->distinct("status");
$builder->distinct(null);

public function forUpdate( bool $forUpdate ): BuilderInterface;
设置 FOR UPDATE 子句

$builder->forUpdate(true);

public function from( mixed $models ): BuilderInterface;
设置参与查询的模型

public function getBindParams(): array;
返回默认绑定参数

public function getBindTypes(): array;
返回默认绑定类型

public function getColumns();
返回要查询的列

public function getDistinct(): bool;
返回 SELECT DISTINCT / SELECT ALL 标志

public function getFrom();
返回参与查询的模型

public function getGroupBy(): array;
返回 GROUP BY 子句

public function getHaving(): string;
返回 HAVING 条件子句

public function getJoins(): array;
返回查询的 JOIN 部分

public function getLimit();
返回当前 LIMIT 子句

public function getModels(): string | array | null;
返回查询涉及的模型

public function getOffset(): int;
返回当前 OFFSET 子句

public function getOrderBy();
返回已设置的 ORDER BY 子句

public function getPhql(): string;
基于构建器参数生成并返回一个 PHQL 语句

public function getQuery(): QueryInterface;
返回构建好的查询

public function getWhere();
返回查询的条件

public function groupBy( mixed $group ): BuilderInterface;
设置 GROUP BY 子句

public function having( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
设置 HAVING 条件子句

public function inWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
将 IN 条件追加到当前条件

public function innerJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
向查询添加 INNER JOIN

public function join( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
向查询添加 :type: JOIN(默认类型 - INNER)

public function leftJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
向查询添加 LEFT JOIN

public function limit( int $limit, mixed $offset = null ): BuilderInterface;
设置 LIMIT 子句

public function notBetweenWhere( string $expr, mixed $minimum, mixed $maximum, string $operator = static-constant-access ): BuilderInterface;
向当前条件追加一个 NOT BETWEEN 条件

public function notInWhere( string $expr, array $values, string $operator = static-constant-access ): BuilderInterface;
向当前条件追加一个 NOT IN 条件

public function offset( int $offset ): BuilderInterface;
设置 OFFSET 子句

public function orWhere( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
使用 OR 运算符向当前条件追加一个条件

public function orderBy( mixed $orderBy ): BuilderInterface;
设置 ORDER BY 条件子句

public function rightJoin( string $model, string $conditions = null, string $alias = null ): BuilderInterface;
向查询添加 RIGHT JOIN

public function setBindParams( array $bindParams, bool $merge = bool ): BuilderInterface;
设置默认绑定参数

public function setBindTypes( array $bindTypes, bool $merge = bool ): BuilderInterface;
设置默认绑定类型

public function where( string $conditions, array $bindParams = [], array $bindTypes = [] ): BuilderInterface;
为查询设置条件

Mvc\Model\Query\LangAbstract

GitHub上的源码

  • 命名空间

    • 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"
);

方法

public static function parsePHQL( string $phql ): array;
解析一个 PHQL 语句并返回中间表示(IR)

Mvc\Model\Query\Status

GitHub上的源码

  • 命名空间

    • 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";
}

属性

/**
 * @var ModelInterface|null
 */
protected $model;

/**
 * @var bool
 */
protected $success;

方法

public function __construct( bool $success, ModelInterface $model = null );
Phalcon\Mvc\Model\Query\Status

public function getMessages(): MessageInterface[];
返回由于操作失败而产生的消息

public function getModel(): ModelInterface;
返回执行操作的模型

public function success(): bool;
允许检查已执行的操作是否成功

Mvc\Model\Query\StatusInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Query
  • 使用

    • Phalcon\Messages\MessageInterface
    • Phalcon\Mvc\ModelInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\Query\StatusInterface

Phalcon\Mvc\Model\Query\Status 的接口

方法

public function getMessages(): MessageInterface[];
返回由操作失败所产生的消息

public function getModel(): ModelInterface;
返回执行操作的模型

public function success(): bool;
允许检查已执行的操作是否成功

Mvc\Model\QueryInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Phalcon\Mvc\ModelInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\QueryInterface

Phalcon\Mvc\Model\Query 的接口

方法

public function cache( array $cacheOptions ): QueryInterface;
设置查询的缓存参数

public function execute( array $bindParams = [], array $bindTypes = [] );
执行已解析的 PHQL 语句

public function getBindParams(): array;
返回默认绑定参数

public function getBindTypes(): array;
返回默认绑定类型

public function getCacheOptions(): array;
返回当前缓存选项

public function getSingleResult( array $bindParams = [], array $bindTypes = [] ): ModelInterface;
执行查询并返回第一个结果

public function getSql(): array;
返回由内部 PHQL 生成的 SQL(仅适用于 SELECT 语句)

public function getUniqueRow(): bool;
检查查询是否被设置为只获取结果集中的第一行

public function parse(): array;
解析 Phalcon\Mvc\Model\Query\Lang 生成的中间代码,生成另一个可由 Phalcon\Mvc\Model\Query 执行的中间表示

public function setBindParams( array $bindParams, bool $merge = bool ): QueryInterface;
设置默认绑定参数

public function setBindTypes( array $bindTypes, bool $merge = bool ): QueryInterface;
设置默认绑定参数

public function setSharedLock( bool $sharedLock = bool ): QueryInterface;
设置 SHARED LOCK 子句

public function setUniqueRow( bool $uniqueRow ): QueryInterface;
告诉查询是否只应返回结果集中的第一行

Mvc\Model\Relation

GitHub上的源码

  • 命名空间

    • 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 = [] );
Phalcon\Mvc\Model\Relation 构造函数

public function getFields();
返回字段

public function getForeignKey();
返回外键配置

public function getIntermediateFields();
获取 has-*-through 关联的中间字段

public function getIntermediateModel(): string;
获取 has-*-through 关联的中间模型

public function getIntermediateReferencedFields();
获取 has-*-through 关联的中间引用字段

public function getOption( string $name );
按指定名称返回一个选项。如果选项不存在则返回 null

public function getOptions(): array;
返回选项

public function getParams();
返回在获取关联记录时必须始终使用的参数

public function getReferencedFields();
返回引用字段

public function getReferencedModel(): string;
返回引用模型

public function getType(): int;
返回关系类型

public function isForeignKey(): bool;
检查关系是否充当外键

public function isReusable(): bool;
检查通过获取 belongs-to/has-many 返回的记录是否在当前请求期间被隐式缓存

public function isThrough(): bool;
检查该关系是否为“多对多”关系

public function setIntermediateRelation( mixed $intermediateFields, string $intermediateModel, mixed $intermediateReferencedFields );
设置 has-*-through 关联的中间模型数据

Mvc\Model\RelationInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\Model\RelationInterface

Phalcon\Mvc\Model\Relation 的接口

方法

public function getFields();
返回字段

public function getForeignKey();
返回外键配置

public function getIntermediateFields();
获取 has-*-through 关联的中间字段

public function getIntermediateModel(): string;
获取 has-*-through 关联的中间模型

public function getIntermediateReferencedFields();
获取 has-*-through 关联的中间引用字段

public function getOption( string $name );
按指定名称返回一个选项。如果选项不存在则返回 null

public function getOptions(): array;
返回选项

public function getParams();
返回在获取关联记录时必须始终使用的参数

public function getReferencedFields();
返回引用字段

public function getReferencedModel(): string;
返回引用模型

public function getType(): int;
返回关系类型

public function isForeignKey(): bool;
检查关系是否充当外键

public function isReusable(): bool;
检查通过获取 belongs-to/has-many 返回的记录是否在当前请求期间被隐式缓存

public function isThrough(): bool;
检查该关系是否为“多对多”关系

public function setIntermediateRelation( mixed $intermediateFields, string $intermediateModel, mixed $intermediateReferencedFields );
设置 has-*-through 关联的中间模型数据

Mvc\Model\ResultInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Phalcon\Mvc\ModelInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\ResultInterface

所有作为基对象传递给结果集的单个对象都必须实现此接口

方法

public function setDirtyState( int $dirtyState ): ModelInterface | bool;
设置对象状态

Mvc\Model\ResultsetAbstract

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( mixed $result, mixed $cache = null );
Phalcon\Mvc\Model\Resultset 构造函数

final public function count(): int;
统计结果集中有多少行

public function delete( Closure $conditionCallback = null ): bool;
删除结果集中的每一条记录

public function filter( callable $filter ): ModelInterface[];
过滤结果集,仅返回开发者需要的内容

$filtered = $robots->filter(
    function ($robot) {
        if ($robot->id < 3) {
            return $robot;
        }
    }
);

public function getCache(): CacheInterface | null;
返回结果集关联的缓存

public function getFirst(): mixed | null;
获取结果集的第一行

$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();

public function getHydrateMode(): int;
返回当前的 hydration 模式

public function getLast(): ModelInterface | null;
获取结果集的最后一行

public function getMessages(): MessageInterface[];
返回批量操作所产生的错误信息

public function getType(): int;
返回结果集正在使用的内部数据检索类型

public function isFresh(): bool;
判断该结果集是新的还是旧的缓存数据

public function jsonSerialize(): array;
以数组形式返回序列化的模型对象,供 json_encode 使用。如果存在则调用每个对象的 jsonSerialize 方法

$robots = Robots::find();

echo json_encode($robots);

public function key(): int | null;
获取结果集中当前行的指针编号

public function next(): void;
将游标移动到结果集的下一行

public function offsetExists( mixed $index ): bool;
检查结果集中是否存在指定的偏移量

public function offsetGet( mixed $index ): mixed;
获取结果集中特定位置的行

public function offsetSet( mixed $offset, mixed $value ): void;
结果集不可更改。此方法仅为了满足 ArrayAccess 接口定义而实现

public function offsetUnset( mixed $offset ): void;
结果集不可更改。此方法仅为了满足 ArrayAccess 接口定义而实现

final public function rewind(): void;
将结果集倒回到开头

final public function seek( mixed $position ): void;
更改结果集内的指针到指定位置。需要时设置新位置,然后设置 this->row

public function setHydrateMode( int $hydrateMode ): ResultsetInterface;
设置结果集的 hydration 模式

public function setIsFresh( bool $isFresh ): ResultsetInterface;
设置判断结果集是否为新的或者旧的缓存数据

public function update( mixed $data, Closure $conditionCallback = null ): bool;
更新结果集中的每一条记录

public function valid(): bool;
检查内部资源是否有可获取的数据行

Mvc\Model\Resultset\Complex

GitHub上的源码

  • 命名空间

    • 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 );
Phalcon\Mvc\Model\Resultset\Complex 构造函数

public function __serialize(): array;
public function __unserialize( array $data ): void;

final public function current(): mixed;
返回结果集中的当前行

public function serialize(): string;
序列化一个结果集会将所有相关行转储到一个大数组中,对其进行序列化并返回生成的字符串

public function toArray(): array;
将整个结果集作为数组返回,若结果集包含大量行,可能会占用比当前更多的内存。

public function unserialize( mixed $data ): void;
反序列化结果集将只允许对保存状态中存在的行进行操作

Mvc\Model\Resultset\Simple

GitHub上的源码

  • 命名空间

    • 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 );
Phalcon\Mvc\Model\Resultset\Simple 构造函数

public function __serialize(): array;
public function __unserialize( array $data ): void;

final public function current(): ModelInterface | null;
返回结果集中的当前行

public function serialize(): string;
序列化一个结果集会将所有相关行转储到一个大数组中

public function toArray( bool $renameColumns = bool ): array;
将整个结果集作为数组返回,若结果集包含大量行,可能会占用比当前更多的内存。导出结果集为数组在大量记录时可能不会更快

public function unserialize( mixed $data ): void;
反序列化结果集将只允许对保存状态中存在的行进行操作

Mvc\Model\ResultsetInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Closure
    • Phalcon\Messages\MessageInterface
    • Phalcon\Mvc\ModelInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\ResultsetInterface

Phalcon\Mvc\Model\Resultset 的接口定义

方法

public function delete( Closure $conditionCallback = null ): bool;
删除结果集中的每一条记录

public function filter( callable $filter ): ModelInterface[];
过滤结果集,仅返回开发者需要的内容

$filtered = $robots->filter(
    function ($robot) {
        if ($robot->id < 3) {
            return $robot;
        }
    }
);

public function getCache(): mixed | null;
返回结果集关联的缓存

public function getFirst(): mixed | null;
获取结果集的第一行

public function getHydrateMode(): int;
返回当前的 hydration 模式

public function getLast(): ModelInterface | null;
获取结果集的最后一行

public function getMessages(): MessageInterface[];
返回批量操作所产生的错误信息

public function getType(): int;
返回结果集正在使用的内部数据检索类型

public function isFresh(): bool;
判断该结果集是新的还是旧的缓存数据

public function setHydrateMode( int $hydrateMode ): ResultsetInterface;
设置结果集的 hydration 模式

public function setIsFresh( bool $isFresh ): ResultsetInterface;
设置判断结果集是否为新的或者旧的缓存数据

public function toArray(): array;
将整个结果集作为数组返回,若结果集包含大量行,可能会占用比当前更多的内存。

public function update( mixed $data, Closure $conditionCallback = null ): bool;
更新结果集中的每一条记录

Mvc\Model\Row

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • ArrayAccess
    • JsonSerializable
    • Phalcon\Mvc\EntityInterface
    • Phalcon\Mvc\ModelInterface
  • 继承

    \stdClass

  • 实现

    • ArrayAccess
    • EntityInterface
    • JsonSerializable
    • ResultInterface

此组件允许 Phalcon\Mvc\Model 返回没有关联实体的行。此对象实现了 ArrayAccess 接口,可用于通过 object->x 或 array[x] 的方式访问对象。

方法

public function jsonSerialize(): array;
序列化对象以供json_encode使用

public function offsetExists( mixed $index ): bool;
检查行中是否存在指定的偏移量

public function offsetGet( mixed $index ): mixed;
获取行内特定位置的记录

public function offsetSet( mixed $offset, mixed $value ): void;
行不能被更改。该功能仅为了满足 ArrayAccess 接口定义而实现

public function offsetUnset( mixed $offset ): void;
行不能被更改。该功能仅为了满足 ArrayAccess 接口定义而实现

public function readAttribute( string $attribute );
按属性名读取属性值

echo $robot->readAttribute("name");

public function setDirtyState( int $dirtyState ): ModelInterface | bool;
设置当前对象的状态

public function toArray(): array;
将实例以数组形式表示出来

public function writeAttribute( string $attribute, mixed $value ): void;
按属性名写入属性值

$robot->writeAttribute("name", "Rosey");

Mvc\Model\Transaction

GitHub上的源码

  • 命名空间

    • 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 );
Phalcon\Mvc\Model\Transaction 构造函数

public function begin(): bool;
启动事务

public function commit(): bool;
提交事务

public function getConnection(): AdapterInterface;
返回与事务相关的连接

public function getMessages(): array;
返回上次保存尝试中的验证消息

public function isManaged(): bool;
检查事务是否由事务管理器管理

public function isValid(): bool;
检查内部连接是否处于活动事务中

public function rollback( string $rollbackMessage = null, ModelInterface $rollbackRecord = null ): bool;
回滚事务

public function setIsNewTransaction( bool $isNew ): void;
设置是否为复用事务或新事务

public function setRollbackOnAbort( bool $rollbackOnAbort ): void;
设置在中止 HTTP 连接时回滚的标志

public function setRollbackedRecord( ModelInterface $record ): void;
设置生成回滚操作的对象

public function setTransactionManager( ManagerInterface $manager ): void;
设置与事务相关的事务管理器

public function throwRollbackException( bool $status ): TransactionInterface;
启用抛出异常

Mvc\Model\Transaction\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Transaction
  • 使用

  • 继承

    \Phalcon\Mvc\Model\Exception

  • 实现

Phalcon\Mvc\Model\Transaction\Exception

Phalcon\Mvc\Model\Transaction 中抛出的异常将使用这个类

Mvc\Model\Transaction\Failed

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Transaction
  • 使用

    • Phalcon\Messages\MessageInterface
    • Phalcon\Mvc\ModelInterface
  • 继承

    Exception

  • 实现

Phalcon\Mvc\Model\Transaction\Failed

发生失败时会抛出此类,用于退出 try/catch 块处理独立事务

属性

/**
 * @var ModelInterface|null
 */
protected $record;

方法

public function __construct( string $message, ModelInterface $record = null );
Phalcon\Mvc\Model\Transaction\Failed 构造函数

public function getRecord(): ModelInterface;
返回阻止事务继续执行的验证记录信息

public function getRecordMessages(): MessageInterface[];
返回阻止事务继续执行的验证记录信息

Mvc\Model\Transaction\Manager

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( DiInterface $container = null );
Phalcon\Mvc\Model\Transaction\Manager 构造函数

public function collectTransactions(): void;
从管理器中移除所有事务

public function commit();
提交管理器内的活动事务

public function get( bool $autoBegin = bool ): TransactionInterface;
返回一个新的 \Phalcon\Mvc\Model\Transaction 或一个已经创建的事务。此方法注册一个关闭函数以回滚活动连接

public function getDI(): DiInterface;
返回依赖注入容器

public function getDbService(): string;
返回用于隔离事务的数据库服务

public function getOrCreateTransaction( bool $autoBegin = bool ): TransactionInterface;
创建/返回一个新的事务或已存在的事务

public function getRollbackPendent(): bool;
检查事务管理器是否注册了一个关闭函数来清理挂起的事务

public function has(): bool;
检查管理器是否有活动的事务

public function notifyCommit( TransactionInterface $transaction ): void;
通知管理器关于已提交的事务

public function notifyRollback( TransactionInterface $transaction ): void;
通知管理器关于已回滚的事务

public function rollback( bool $collect = bool ): void;
回滚管理器内的活动事务。Collect 将从管理器中移除事务

public function rollbackPendent(): void;
回滚管理器内的活动事务

public function setDI( DiInterface $container ): void;
设置依赖注入容器

public function setDbService( string $service ): ManagerInterface;
设置用于运行隔离事务的数据库服务

public function setRollbackPendent( bool $rollbackPendent ): ManagerInterface;
设置事务管理器是否必须注册一个关闭函数来清理挂起的事务

protected function collectTransaction( TransactionInterface $transaction ): void;
从 TransactionManager 中移除事务

Mvc\Model\Transaction\ManagerInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model\Transaction
  • 使用

    • Phalcon\Mvc\Model\TransactionInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\Transaction\ManagerInterface

Phalcon\Mvc\Model\Transaction\Manager 的接口

方法

public function collectTransactions(): void;
从管理器中移除所有事务

public function commit();
提交管理器内的活动事务

public function get( bool $autoBegin = bool ): TransactionInterface;
返回一个新的 \Phalcon\Mvc\Model\Transaction 或一个已经创建的事务

public function getDbService(): string;
返回用于隔离事务的数据库服务

public function getRollbackPendent(): bool;
检查事务管理器是否注册了一个关闭函数来清理挂起的事务

public function has(): bool;
检查管理器是否有活动的事务

public function notifyCommit( TransactionInterface $transaction ): void;
通知管理器关于已提交的事务

public function notifyRollback( TransactionInterface $transaction ): void;
通知管理器关于已回滚的事务

public function rollback( bool $collect = bool ): void;
回滚管理器内的活动事务。Collect 将从管理器中移除事务

public function rollbackPendent(): void;
回滚管理器内的活动事务

public function setDbService( string $service ): ManagerInterface;
设置用于运行隔离事务的数据库服务

public function setRollbackPendent( bool $rollbackPendent ): ManagerInterface;
设置事务管理器是否必须注册一个关闭函数来清理挂起的事务

Mvc\Model\TransactionInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Phalcon\Mvc\ModelInterface
    • Phalcon\Mvc\Model\Transaction\ManagerInterface
  • 继承

  • 实现

Phalcon\Mvc\Model\TransactionInterface

Phalcon\Mvc\Model\Transaction 的接口

方法

public function begin(): bool;
启动事务

public function commit(): bool;
提交事务

public function getConnection(): \Phalcon\Db\Adapter\AdapterInterface;
返回与事务相关的连接

public function getMessages(): array;
返回上次保存尝试中的验证消息

public function isManaged(): bool;
检查事务是否由事务管理器管理

public function isValid(): bool;
检查内部连接是否处于活动事务中

public function rollback( string $rollbackMessage = null, ModelInterface $rollbackRecord = null ): bool;
回滚事务

public function setIsNewTransaction( bool $isNew ): void;
设置是否为复用事务或新事务

public function setRollbackOnAbort( bool $rollbackOnAbort ): void;
设置在中止 HTTP 连接时回滚的标志

public function setRollbackedRecord( ModelInterface $record ): void;
设置生成回滚操作的对象

public function setTransactionManager( ManagerInterface $manager ): void;
设置与事务相关的事务管理器

public function throwRollbackException( bool $status ): TransactionInterface;
启用抛出异常

Mvc\Model\ValidationFailed

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Model
  • 使用

    • Phalcon\Messages\Message
    • Phalcon\Mvc\ModelInterface
  • 继承

    Exception

  • 实现

Phalcon\Mvc\Model\ValidationFailed

当模型保存记录失败时会生成此异常。Phalcon\Mvc\Model 必须配置为此行为

属性

/**
 * @var array
 */
protected $messages;

/**
 * @var ModelInterface
 */
protected $model;

方法

public function __construct( ModelInterface $model, array $validationMessages );
Phalcon\Mvc\Model\ValidationFailed 构造函数

public function getMessages(): Message[];
返回验证过程中产生的完整消息组

public function getModel(): ModelInterface;
返回生成消息的模型

Mvc\ModelInterfaceInterface

GitHub上的源码

  • 命名空间

    • 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 appendMessage( MessageInterface $message ): ModelInterface;
在验证过程中添加自定义消息

public function assign( array $data, mixed $whiteList = null, mixed $dataColumnMap = null ): ModelInterface;
从数组中分配值给模型

public static function average( array $parameters = [] ): double | ResultsetInterface;
允许计算符合指定条件列的平均值

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;
从数组赋值给模型并返回新模型

public static function cloneResultMapHydrate( array $data, mixed $columnMap, int $hydrationMode );
根据数据和列映射返回一个填充的结果

public static function count( mixed $parameters = null ): int | ResultsetInterface;
允许计算符合指定条件的记录数量

返回一个整数用于简单查询,或当使用 GROUP 条件时返回一个 ResultsetInterface 实例。结果将包含每组的数量。

public function create(): bool;
插入一个模型实例。如果该实例已经在持久化中存在,则会抛出异常。成功返回 true,否则返回 false。

public function delete(): bool;
删除模型实例。成功时返回true,否则返回false。

public static function find( mixed $parameters = null );
允许查询符合指定条件的一组记录

public static function findFirst( mixed $parameters = null ): mixed | null;
允许查询符合指定条件的第一条记录

public function fireEvent( string $eventName ): bool;
触发事件,隐式调用行为和事件管理器中的监听者会被通知

public function fireEventCancel( string $eventName ): bool;
触发事件,隐式调用行为和事件管理器中的监听者会被通知。如果其中一个回调/监听者返回 bool false,此方法将停止执行

public function getDirtyState(): int;
返回 DIRTY_STATE_* 常量之一,说明记录是否存在于数据库中

public function getMessages(): MessageInterface[];
返回验证消息数组

public function getModelsMetaData(): MetaDataInterface;
返回与实体实例相关的模型元数据服务

public function getOperationMade(): int;
返回 ORM 执行的最新操作类型。返回 OP_* 类常量之一

public function getReadConnection(): AdapterInterface;
获取内部数据库连接

public function getReadConnectionService(): string;
返回用于读取数据的 DependencyInjection 连接服务

public function getRelated( string $alias, mixed $arguments = null );
根据定义的关系返回相关记录

public function getSchema(): string | null;
返回表映射所在模式的名称

public function getSource(): string;
返回模型中映射的表名

public function getWriteConnection(): AdapterInterface;
获取内部数据库连接

public function getWriteConnectionService(): string;
返回用于写入数据的 DependencyInjection 连接服务

public static function maximum( mixed $parameters = null ): mixed;
允许获取符合指定条件列的最大值

public static function minimum( mixed $parameters = null ): mixed;
允许获取符合指定条件列的最小值

public static function query( DiInterface $container = null ): CriteriaInterface;
为特定模型创建一个查询条件

public function refresh(): ModelInterface;
刷新模型属性,从数据库重新查询记录

public function save(): bool;
插入或更新一个模型实例。成功返回 true,否则返回 false。

public function setConnectionService( string $connectionService ): void;
设置读写连接服务

public function setDirtyState( int $dirtyState ): ModelInterface | bool;
使用 DIRTY_STATE_* 常量之一设置对象的脏状态

public function setReadConnectionService( string $connectionService ): void;
设置用于读取数据的 DependencyInjection 连接服务

public function setSnapshotData( array $data, mixed $columnMap = null ): void;
设置记录的快照数据。此方法由内部调用,用于当模型配置了保留快照数据时设置快照数据

public function setTransaction( TransactionInterface $transaction ): ModelInterface;
设置与模型实例相关联的事务

public function setWriteConnectionService( string $connectionService ): void;
设置用于写入数据的 DependencyInjection 连接服务

public function skipOperation( bool $skip ): void;
强制跳过当前操作并进入成功状态

public static function sum( mixed $parameters = null ): double | ResultsetInterface;
允许计算与指定条件匹配的列的总和

public function update(): bool;
更新模型实例。如果该实例在持久化存储中不存在,将抛出异常。成功时返回 true,否则返回 false。

public function validationHasFailed(): bool;
检查验证过程是否生成了任何消息

Mvc\ModuleDefinitionInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc
  • 使用

    • Phalcon\Di\DiInterface
  • 继承

  • 实现

Phalcon\Mvc\ModuleDefinitionInterface

此接口必须由类模块定义实现

方法

public function registerAutoloaders( DiInterface $container = null );
注册与模块相关的自动加载器

public function registerServices( DiInterface $container );
注册与模块相关的服务

Mvc\Router

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( bool $defaultRoutes = bool );
Phalcon\Mvc\Router 构造函数

public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null, int $position = static-constant-access ): RouteInterface;
添加一个没有 HTTP 限制的路由到路由器

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;
添加一条仅当HTTP方法为CONNECT时才匹配的路由

public function addDelete( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为DELETE时才匹配的路由

public function addGet( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为GET时才匹配的路由

public function addHead( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为HEAD时才匹配的路由

public function addOptions( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为OPTIONS时才匹配的路由

public function addPatch( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为PATCH时才匹配的路由

public function addPost( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为POST时才匹配的路由

public function addPurge( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为PURGE时才匹配的路由(支持Squid和Varnish)

public function addPut( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为PUT时才匹配的路由

public function addTrace( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为TRACE时才匹配的路由

public function attach( RouteInterface $route, int $position = static-constant-access ): RouterInterface;
将Route对象附加到路由栈。

use Phalcon\Mvc\Router;
use Phalcon\Mvc\Router\Route;

class CustomRoute extends Route {
     // ...
}

$router = new Router();

$router->attach(
    new CustomRoute("/about", "About::index", ["GET", "HEAD"]),
    Router::POSITION_FIRST
);

public function clear(): void;
移除所有预定义的路由

public function getActionName(): string;
返回已处理的动作名称

public function getControllerName(): string;
返回已处理的控制器名称

public function getDefaults(): array;
返回默认参数数组

public function getEventsManager(): ManagerInterface | null;
返回内部事件管理器

public function getKeyRouteIds(): array;
public function getKeyRouteNames(): array;

public function getMatchedRoute(): RouteInterface | null;
返回匹配处理URI的路由

public function getMatches(): array;
返回正则表达式匹配的子表达式

public function getModuleName(): string;
返回已处理的模块名称

public function getNamespaceName(): string;
返回已处理的命名空间名称

public function getParams(): array;
返回已处理的参数

public function getRewriteUri(): string;
获取重写信息。此信息是从 $_GET["_url"] 中读取的。如果无法读取重写信息,则返回 '/'

public function getRouteById( mixed $id ): RouteInterface | bool;
根据ID返回路由对象

public function getRouteByName( string $name ): RouteInterface | bool;
根据名称返回路由对象

public function getRoutes(): RouteInterface[];
返回在路由器中定义的所有路由

public function handle( string $uri ): void;
处理从重写引擎接收到的路由信息

// Passing a URL
$router->handle("/posts/edit/1");

public function isExactControllerName(): bool;
返回控制器名称是否不应被修改

public function mount( GroupInterface $group ): RouterInterface;
在路由器中挂载一组路由

public function notFound( mixed $paths ): RouterInterface;
设置当未匹配到任何定义的路由时返回的一组路径

public function removeExtraSlashes( bool $remove ): RouterInterface;
设置路由器是否必须移除处理路由中的多余斜杠

public function setDefaultAction( string $actionName ): RouterInterface;
设置默认的动作名称

public function setDefaultController( string $controllerName ): RouterInterface;
设置默认控制器名

public function setDefaultModule( string $moduleName ): RouterInterface;
设置默认模块名

public function setDefaultNamespace( string $namespaceName ): RouterInterface;
设置默认命名空间的名称

@parma string namespaceName

public function setDefaults( array $defaults ): RouterInterface;
设置默认路径数组。如果路由缺少路径,路由器将使用此处定义的路径。此方法不应用于设置404路由

$router->setDefaults(
    [
        "module" => "common",
        "action" => "index",
    ]
);

public function setEventsManager( ManagerInterface $eventsManager ): void;
设置事件管理器

public function setKeyRouteIds( array $routeIds ): Router;
public function setKeyRouteNames( array $routeNames ): Router;

public function setUriSource( int $uriSource ): Router;
设置 URI 源。选择其中一个 URI_SOURCE_* 常量

$router->setUriSource(
    Router::URI_SOURCE_SERVER_REQUEST_URI
);

public function wasMatched(): bool;
检查路由器是否匹配任何已定义的路由

protected function extractRealUri( string $uri ): string;

Mvc\Router\Annotations

GitHub上的源码

  • 命名空间

    • 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 addResource( string $handler, string $prefix = null ): Annotations;
向注解处理器添加一个资源。资源是一个包含路由注解的类

public function getActionPreformatCallback();

public function getResources(): array;
返回已注册的资源

public function handle( string $uri ): void;
根据重写信息生成路由参数

public function processActionAnnotation( string $module, string $namespaceName, string $controller, string $action, Annotation $annotation ): void;
检查控制器的公共方法中的注解

public function processControllerAnnotation( string $handler, Annotation $annotation );
检查控制器文档块中的注解

public function setActionPreformatCallback( mixed $callback = null );
设置动作预格式化回调函数。此处的动作名已经不带 'Action' 后缀

// Array as callback
$annotationRouter->setActionPreformatCallback(
     [
         new Uncamelize(),
         '__invoke'
     ]
 );

// Function as callback
$annotationRouter->setActionPreformatCallback(
    function ($action) {
        return $action;
    }
);

// String as callback
$annotationRouter->setActionPreformatCallback('strtolower');

// If empty method constructor called [null], sets uncamelize with - delimiter
$annotationRouter->setActionPreformatCallback();

public function setActionSuffix( string $actionSuffix );
更改动作方法后缀

public function setControllerSuffix( string $controllerSuffix );
更改控制器类后缀

Mvc\Router\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Router
  • 使用

  • 继承

    \Exception

  • 实现

Phalcon\Mvc\Router\Exception

Phalcon\Mvc\Router 中抛出的异常会使用此类

Mvc\Router\Group

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( mixed $paths = null );
Phalcon\Mvc\Router\Group 构造函数

public function add( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
在任何HTTP方法上向路由器添加路由

$router->add("/about", "About::index");

public function addConnect( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为CONNECT时才匹配的路由

public function addDelete( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为DELETE时才匹配的路由

public function addGet( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为GET时才匹配的路由

public function addHead( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为HEAD时才匹配的路由

public function addOptions( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为OPTIONS时才匹配的路由

public function addPatch( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为PATCH时才匹配的路由

public function addPost( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为POST时才匹配的路由

public function addPurge( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅在 HTTP 方法为 PURGE 时才匹配的路由

public function addPut( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为PUT时才匹配的路由

public function addTrace( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为TRACE时才匹配的路由

public function beforeMatch( callable $beforeMatch ): GroupInterface;
设置在路由匹配时调用的回调。开发人员可以在此处实现任何任意条件。如果回调返回false,则认为路由未匹配

public function clear(): void;
移除所有预定义的路由

public function getBeforeMatch(): callable;
如果存在,返回"before match"回调

public function getHostname(): string | null;
返回主机名限制

public function getPaths(): array | string;
返回为此组定义的通用路径

public function getPrefix(): string;
返回所有路由的通用前缀

public function getRoutes(): RouteInterface[];
返回添加到该组的路由

public function setHostname( string $hostname ): GroupInterface;
为该组中的所有路由设置主机名限制

public function setPaths( mixed $paths ): GroupInterface;
为该组中的所有路由设置通用路径

public function setPrefix( string $prefix ): GroupInterface;
为该组中的所有路由设置通用 URI 前缀

protected function addRoute( string $pattern, mixed $paths = null, mixed $httpMethods = null ): RouteInterface;
应用通用属性添加一条路由

Mvc\Router\GroupInterfaceInterface

GitHub上的源码

  • 命名空间

    • 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;
在任何HTTP方法上向路由器添加路由

router->add("/about", "About::index");

public function addConnect( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为CONNECT时才匹配的路由

public function addDelete( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为DELETE时才匹配的路由

public function addGet( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为GET时才匹配的路由

public function addHead( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为HEAD时才匹配的路由

public function addOptions( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为OPTIONS时才匹配的路由

public function addPatch( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为PATCH时才匹配的路由

public function addPost( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为POST时才匹配的路由

public function addPurge( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅在 HTTP 方法为 PURGE 时才匹配的路由

public function addPut( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为PUT时才匹配的路由

public function addTrace( string $pattern, mixed $paths = null ): RouteInterface;
添加一条仅当HTTP方法为TRACE时才匹配的路由

public function beforeMatch( callable $beforeMatch ): GroupInterface;
设置在路由匹配时调用的回调。开发人员可以在此处实现任何任意条件。如果回调返回false,则认为路由未匹配

public function clear(): void;
移除所有预定义的路由

public function getBeforeMatch(): callable;
如果存在,返回"before match"回调

public function getHostname(): string | null;
返回主机名限制

public function getPaths(): array | string;
返回为此组定义的通用路径

public function getPrefix(): string;
返回所有路由的通用前缀

public function getRoutes(): RouteInterface[];
返回添加到该组的路由

public function setHostname( string $hostname ): GroupInterface;
为该组中的所有路由设置主机名限制

public function setPaths( mixed $paths ): GroupInterface;
为该组中的所有路由设置通用路径

public function setPrefix( string $prefix ): GroupInterface;
为该组中的所有路由设置通用 URI 前缀

Mvc\路由器\路线

GitHub上的源码

  • 命名空间

    • 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 = ;

方法

public function __construct( string $pattern, mixed $paths = null, mixed $httpMethods = null );
Phalcon\Mvc\Router\Route 构造函数

public function beforeMatch( callable $callback ): RouteInterface;
设置在路由匹配时调用的回调。开发人员可以在此处实现任何任意条件。如果回调返回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;
    }
);

public function compilePattern( string $pattern ): string;
替换模式中的占位符,返回有效的PCRE正则表达式

public function convert( string $name, mixed $converter ): RouteInterface;

public function extractNamedParams( string $pattern ): array | bool;
从字符串中提取参数

public function getBeforeMatch(): callable;
如果存在,返回"before match"回调

public function getCompiledPattern(): string;
返回路由的编译模式

public function getConverters(): array;
返回路由器转换器

public function getGroup(): GroupInterface | null;
返回与该路由关联的组

public function getHostname(): string | null;
如果存在,返回主机名限制

public function getHttpMethods(): array | string;
返回约束匹配此路由的HTTP方法

public function getId(): string;

public function getMatch(): callable;
如果存在,返回'match'回调

public function getName(): string | null;
返回路由的名称

public function getPaths(): array;
返回路径

public function getPattern(): string;
返回路由的模式

public function getReversedPaths(): array;
返回使用位置作为键和名称作为值的路径

public function getRouteId(): string;
返回路由的ID

public static function getRoutePaths( mixed $paths = null ): array;
返回routePaths

public function match( mixed $callback ): RouteInterface;
允许设置一个回调以直接在路由中处理请求

$router->add(
    "/help",
    []
)->match(
    function () {
        return $this->getResponse()->redirect("https://support.google.com/", true);
    }
);

public function reConfigure( string $pattern, mixed $paths = null ): void;
重新配置路由,添加新模式和一组路径

public static function reset(): void;
重置内部路由ID生成器

public function setGroup( GroupInterface $group ): RouteInterface;
设置与该路由关联的组

public function setHostname( string $hostname ): RouteInterface;
为此路由设置主机名限制

$route->setHostname("localhost");

public function setHttpMethods( mixed $httpMethods ): RouteInterface;
设置一组约束该路由匹配的HTTP方法(via的别名)

$route->setHttpMethods("GET");

$route->setHttpMethods(
    [
        "GET",
        "POST",
    ]
);

public function setName( string $name ): RouteInterface;
设置路由的名称

$router->add(
    "/about",
    [
        "controller" => "about",
    ]
)->setName("about");

public function via( mixed $httpMethods ): RouteInterface;
设置一个或多个约束该路由匹配的HTTP方法

$route->via("GET");

$route->via(
    [
        "GET",
        "POST",
    ]
);

Mvc\路由器\路线接口Interface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Router
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\Router\RouteInterface

Phalcon\Mvc\Router\Route 的接口

方法

public function compilePattern( string $pattern ): string;
替换模式中的占位符,返回有效的PCRE正则表达式

public function convert( string $name, mixed $converter ): RouteInterface;
添加转换器以对特定参数执行额外转换

public function getCompiledPattern(): string;
返回路由的模式

public function getHostname(): string | null;
如果存在,返回主机名限制

public function getHttpMethods(): string | array;
返回约束匹配此路由的HTTP方法

public function getName(): string | null;
返回路由的名称

public function getPaths(): array;
返回路径

public function getPattern(): string;
返回路由的模式

public function getReversedPaths(): array;
返回使用位置作为键和名称作为值的路径

public function getRouteId(): string;
返回路由的ID

public function reConfigure( string $pattern, mixed $paths = null ): void;
重新配置路由,添加新模式和一组路径

public static function reset(): void;
重置内部路由ID生成器

public function setHostname( string $hostname ): RouteInterface;
为此路由设置主机名限制

public function setHttpMethods( mixed $httpMethods ): RouteInterface;
设置一组约束该路由匹配的HTTP方法

public function setName( string $name ): RouteInterface;
设置路由的名称

public function via( mixed $httpMethods ): RouteInterface;
设置一个或多个约束该路由匹配的HTTP方法

Mvc\路由器接口Interface

GitHub上的源码

  • 命名空间

    • 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;
在任何HTTP方法上向路由器添加路由

public function addConnect( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为CONNECT时才匹配的路由

public function addDelete( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为DELETE时才匹配的路由

public function addGet( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为GET时才匹配的路由

public function addHead( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为HEAD时才匹配的路由

public function addOptions( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为OPTIONS时才匹配的路由

public function addPatch( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为PATCH时才匹配的路由

public function addPost( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为POST时才匹配的路由

public function addPurge( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为PURGE时才匹配的路由(支持Squid和Varnish)

public function addPut( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为PUT时才匹配的路由

public function addTrace( string $pattern, mixed $paths = null, int $position = static-constant-access ): RouteInterface;
添加一条仅当HTTP方法为TRACE时才匹配的路由

public function attach( RouteInterface $route, int $position = static-constant-access ): RouterInterface;
将Route对象附加到路由栈。

public function clear(): void;
移除所有已定义的路由

public function getActionName(): string;
返回处理后的动作名

public function getControllerName(): string;
返回已处理的控制器名称

public function getMatchedRoute(): RouteInterface | null;
返回匹配处理URI的路由

public function getMatches(): array;
返回正则表达式匹配的子表达式

public function getModuleName(): string;
返回处理后的模块名

public function getNamespaceName(): string;
返回已处理的命名空间名称

public function getParams(): array;
返回处理后的额外参数

public function getRouteById( mixed $id ): RouteInterface | bool;
根据ID返回路由对象

public function getRouteByName( string $name ): RouteInterface | bool;
根据名称返回路由对象

public function getRoutes(): RouteInterface[];
返回路由器中定义的所有路由

public function handle( string $uri ): void;
处理从重写引擎接收到的路由信息

public function mount( GroupInterface $group ): RouterInterface;
在路由器中挂载一组路由

public function setDefaultAction( string $actionName ): RouterInterface;
设置默认的动作名称

public function setDefaultController( string $controllerName ): RouterInterface;
设置默认控制器名

public function setDefaultModule( string $moduleName ): RouterInterface;
设置默认模块名

public function setDefaults( array $defaults ): RouterInterface;
设置默认路径数组

public function wasMatched(): bool;
检查路由器是否匹配任何已定义的路由

Mvc\网址

GitHub上的源码

  • 命名空间

    • 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 __construct( RouterInterface $router = null );

public function get( mixed $uri = null, mixed $args = null, bool $local = null, mixed $baseUri = null ): string;
生成一个URL

// Generate a URL appending the URI to the base URI
echo $url->get("products/edit/1");

// Generate a URL for a predefined route
echo $url->get(
    [
        "for"   => "blog-post",
        "title" => "some-cool-stuff",
        "year"  => "2015",
    ]
);

// Generate a URL with GET arguments (/show/products?id=1&name=Carrots)
echo $url->get(
    "show/products",
    [
        "id"   => 1,
        "name" => "Carrots",
    ]
);

// Generate an absolute URL by setting the third parameter as false.
echo $url->get(
    "https://phalcon.io/",
    null,
    false
);

public function getBasePath(): string;
返回基础路径

public function getBaseUri(): string;
返回所有生成的URL的前缀。默认为 /

public function getStatic( mixed $uri = null ): string;
为静态资源生成一个URL

// 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",
    ]
);

public function getStaticBaseUri(): string;
返回所有生成的静态URL的前缀。默认为 /

public function path( string $path = null ): string;
生成一个本地路径

public function setBasePath( string $basePath ): UrlInterface;
为所有生成的路径设置一个基础路径

$url->setBasePath("/var/www/htdocs/");

public function setBaseUri( string $baseUri ): UrlInterface;
为所有要生成的URI设置一个前缀

$url->setBaseUri("/invo/");

$url->setBaseUri("/invo/index.php/");

public function setStaticBaseUri( string $staticBaseUri ): UrlInterface;
为所有生成的静态URL设置一个前缀

$url->setStaticBaseUri("/invo/");

Mvc\Url\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Url
  • 使用

  • 继承

    \Exception

  • 实现

Phalcon\Mvc\Url\Exception

Phalcon\Mvc\Url 中抛出的异常将使用此类

Mvc\Url\UrlInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\Url
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\Url\UrlInterface 的接口

方法

public function get( mixed $uri = null, mixed $args = null, bool $local = null ): string;
生成一个URL

public function getBasePath(): string;
返回一个基础路径

public function getBaseUri(): string;
返回所有生成的URL的前缀。默认为 /

public function path( string $path = null ): string;
生成一个本地路径

public function setBasePath( string $basePath ): UrlInterface;
为所有生成的路径设置基础路径

public function setBaseUri( string $baseUri ): UrlInterface;
为所有生成的URL设置一个前缀

Mvc\View

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( array $options = [] );
Phalcon\Mvc\View 构造函数

public function __get( string $key ): mixed | null;
魔术方法,用于检索传递给视图的变量

echo $this->view->products;

public function __isset( string $key ): bool;
魔术方法,用于检查视图中是否设置了某个变量

echo isset($this->view->products);

public function __set( string $key, mixed $value );
魔术方法,用于将变量传递给视图

$this->view->products = $products;

public function cleanTemplateAfter(): View;
重置所有“before”模板布局

public function cleanTemplateBefore(): View;
重置所有“before”模板布局

public function disable(): View;
禁用自动渲染进程

public function disableLevel( mixed $level ): ViewInterface;
禁用特定级别的渲染

// Render all levels except ACTION level
$this->view->disableLevel(
    View::LEVEL_ACTION_VIEW
);

public function enable(): View;
启用自动渲染进程

public function exists( string $view ): bool;
检查视图是否存在 @deprecated

public function finish(): View;
通过停止输出缓冲结束渲染过程

public function getActionName(): string;
获取已渲染动作的名称

public function getActiveRenderPath(): string | array;
返回当前渲染视图的路径(或多个路径)

public function getBasePath(): string;
获取基础路径

public function getContent(): string;
返回另一个视图阶段的输出

public function getControllerName(): string;
获取已渲染控制器的名称

public function getCurrentRenderLevel(): int;

public function getEventsManager(): ManagerInterface | null;
返回内部事件管理器

public function getLayout(): string;
返回主视图的名称

public function getLayoutsDir(): string;
获取当前布局子目录

public function getMainView(): string;
返回主视图的名称

public function getParamsToView(): array;
返回传递给视图的参数

public function getPartial( string $partialPath, mixed $params = null ): string;
渲染一个局部视图

// Retrieve the contents of a partial
echo $this->getPartial("shared/footer");
// Retrieve the contents of a partial with arguments
echo $this->getPartial(
    "shared/footer",
    [
        "content" => $html,
    ]
);

public function getPartialsDir(): string;
获取当前局部视图子目录

public function getRegisteredEngines(): array;

public function getRender( string $controllerName, string $actionName, array $params = [], mixed $configCallback = null ): string;
执行自动渲染并将输出作为字符串返回

$template = $this->view->getRender(
    "products",
    "show",
    [
        "products" => $products,
    ]
);
public function getRenderLevel(): int;

public function getVar( string $key ): mixed | null;
返回之前在视图中设置的参数

public function getViewsDir(): string | array;
获取视图目录

public function has( string $view ): bool;
检查视图是否存在

public function isDisabled(): bool;
是否启用了自动渲染

public function partial( string $partialPath, mixed $params = null );
渲染一个局部视图

// Show a partial inside another view
$this->partial("shared/footer");
// Show a partial inside another view with parameters
$this->partial(
    "shared/footer",
    [
        "content" => $html,
    ]
);

public function pick( mixed $renderView ): View;
选择一个不同的视图进行渲染,而不是最后控制器/最后动作对应的视图

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;
处理视图和模板;如果需要则触发事件

public function registerEngines( array $engines ): View;
注册模板引擎

$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();

public function reset(): View;
将视图组件重置为出厂默认值

public function setBasePath( string $basePath ): View;
设置基础路径。根据您的平台,始终添加一个尾随斜杠或反斜杠

$view->setBasePath(__DIR__ . "/");

public function setContent( string $content ): View;
外部设置视图内容

$this->view->setContent("<h1>hello</h1>");

public function setEventsManager( ManagerInterface $eventsManager ): void;
设置事件管理器

public function setLayout( string $layout ): View;
更改使用的布局,而不是使用最新控制器的名称

$this->view->setLayout("main");

public function setLayoutsDir( string $layoutsDir ): View;
设置布局子目录。必须是位于视图目录下的目录。根据您的平台,始终添加一个尾随斜杠或反斜杠

$view->setLayoutsDir("../common/layouts/");

public function setMainView( string $viewPath ): View;
设置默认视图名称。它必须是一个没有扩展名的文件,并且位于视图目录下

// Renders as main view views-dir/base.phtml
$this->view->setMainView("base");

public function setParamToView( string $key, mixed $value ): View;
向视图添加参数(setVar 的别名)

$this->view->setParamToView("products", $products);

public function setPartialsDir( string $partialsDir ): View;
设置局部视图子目录。必须是位于视图目录下的目录。根据您的平台,始终添加一个尾随斜杠或反斜杠

$view->setPartialsDir("../common/partials/");

public function setRenderLevel( int $level ): ViewInterface;
设置视图的渲染层级

// Render the view related to the controller only
$this->view->setRenderLevel(
    View::LEVEL_LAYOUT
);

public function setTemplateAfter( mixed $templateAfter ): View;
设置一个“after”模板控制器布局

public function setTemplateBefore( mixed $templateBefore ): View;
在控制器布局前设置一个模板

public function setVar( string $key, mixed $value ): View;
设置单个视图参数

$this->view->setVar("products", $products);

public function setVars( array $params, bool $merge = bool ): View;
设置所有渲染参数

$this->view->setVars(
    [
        "products" => $products,
    ]
);

public function setViewsDir( mixed $viewsDir ): View;
设置视图目录。根据您的平台,始终添加尾随斜杠或反斜杠

public function start(): View;
开始渲染过程并启用输出缓冲

public function toString( string $controllerName, string $actionName, array $params = [] ): string;
渲染视图并将其作为字符串返回

protected function engineRender( array $engines, string $viewPath, bool $silence, bool $mustClean = bool );
在已注册扩展中检查视图是否存在并渲染它

protected function getViewsDirs(): array;
获取多个视图目录

final protected function isAbsolutePath( string $path );
检查路径是否为绝对路径

protected function loadTemplateEngines(): array;
加载已注册的模板引擎,如果没有注册,则会使用 Phalcon\Mvc\View\Engine\Php

Mvc\View\Engine\AbstractEngineAbstract

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\View\Engine
  • 使用

    • Phalcon\Di\DiInterface
    • Phalcon\Di\Injectable
    • Phalcon\Mvc\ViewBaseInterface
  • 继承

    Injectable

  • 实现

    • EngineInterface

所有模板引擎适配器都必须继承此类。这提供了引擎与 Phalcon\Mvc\View 组件之间的基本接口。

属性

/**
 * @var ViewBaseInterface
 */
protected $view;

方法

public function __construct( ViewBaseInterface $view, DiInterface $container = null );
Phalcon\Mvc\View\Engine 构造函数

public function getContent(): string;
返回另一个视图阶段的缓存输出

public function getView(): ViewBaseInterface;
返回与适配器相关的视图组件

public function partial( string $partialPath, mixed $params = null ): void;
渲染另一个视图中的局部内容

Mvc\View\Engine\EngineInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\View\Engine
  • 使用

  • 继承

  • 实现

Phalcon\Mvc\View 引擎适配器的接口

方法

public function getContent(): string;
返回另一个视图阶段的缓存输出

public function partial( string $partialPath, mixed $params = null ): void;
渲染另一个视图中的局部内容

public function render( string $path, mixed $params, bool $mustClean = bool );
使用模板引擎渲染视图

TODO:将参数更改为数组类型

Mvc\View\Engine\Php

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\View\Engine
  • 使用

  • 继承

    AbstractEngine

  • 实现

使用PHP本身作为模板引擎的适配器

方法

public function render( string $path, mixed $params, bool $mustClean = bool );
使用模板引擎渲染视图

Mvc\View\Engine\Volt

GitHub上的源码

  • 命名空间

    • 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;

方法

public function callMacro( string $name, array $arguments = [] ): mixed;
检查宏是否定义并调用它

public function convertEncoding( string $text, string $from, string $to ): string;
执行字符串转换

public function getCompiler(): Compiler;
返回 Volt 的编译器

public function getEventsManager(): ManagerInterface | null;
返回内部事件管理器

public function getOptions(): array;
返回 Volt 的选项

public function isIncluded( mixed $needle, mixed $haystack ): bool;
检查needle是否包含在haystack中

public function length( mixed $item ): int;
长度过滤器。如果传递的是数组/对象则执行 count,否则执行 strlen/mb_strlen

public function preload( mixed $parameters ): string;
解析预加载元素并设置必要的链接头 @todo 寻找更好的方式来处理这个

public function render( string $path, mixed $params, bool $mustClean = bool );
使用模板引擎渲染视图

public function setEventsManager( ManagerInterface $eventsManager ): void;
设置事件管理器

public function setOptions( array $options );
设置 Volt 的选项

public function slice( mixed $value, int $start = int, mixed $end = null );
从字符串/数组/可遍历对象值中提取一个切片

public function sort( array $value ): array;
对数组进行排序

Mvc\View\Engine\Volt\Compiler

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( ViewBaseInterface $view = null );
Phalcon\Mvc\View\Engine\Volt\Compiler

public function addExtension( mixed $extension ): Compiler;
注册一个Volt扩展

@var mixed 扩展

public function addFilter( string $name, mixed $definition ): Compiler;
在编译器中注册一个新过滤器

public function addFunction( string $name, mixed $definition ): Compiler;
在编译器中注册一个新函数

public function attributeReader( array $expr ): string;
解析属性读取

public function compile( string $templatePath, bool $extendsMode = bool );
应用编译器选项将模板编译成文件 此方法不会返回未被编译的模板的编译路径

$compiler->compile("views/layouts/main.volt");

require $compiler->getCompiledTemplatePath();

public function compileAutoEscape( array $statement, bool $extendsMode ): string;
编译"autoescape"语句并返回PHP代码

public function compileCall( array $statement, bool $extendsMode );
编译宏调用

public function compileCase( array $statement, bool $caseClause = bool ): string;
编译"case"/"default"子句并返回PHP代码

public function compileDo( array $statement ): string;
编译"do"语句并返回PHP代码

public function compileEcho( array $statement ): string;
编译 {% raw %}{{ }}语句并返回 PHP 代码

public function compileElseIf( array $statement ): string;
编译"elseif"语句并返回PHP代码

public function compileFile( string $path, string $compiledPath, bool $extendsMode = bool );
将模板编译成文件并强制指定目标路径

$compiler->compileFile(
    "views/layouts/main.volt",
    "views/layouts/main.volt.php"
);

public function compileForElse(): string;
生成一个 'forelse' 的 PHP 代码

public function compileForeach( array $statement, bool $extendsMode = bool ): string;
将 "foreach" 中间代码表示编译为普通 PHP 代码

public function compileIf( array $statement, bool $extendsMode = bool ): string;
编译一个返回 PHP 代码的 'if' 语句

public function compileInclude( array $statement ): string;
编译一个返回 PHP 代码的 'include' 语句

public function compileMacro( array $statement, bool $extendsMode ): string;
编译宏

public function compileReturn( array $statement ): string;
编译一个返回 PHP 代码的 "return" 语句

@throws \Phalcon\Mvc\View\Engine\Volt\Exception

public function compileSet( array $statement ): string;
编译 "set" 语句并返回 PHP 代码。该方法接受由 Volt 解析器生成的数组并创建相应的setPHP 语句。由于需要对 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]; ?>";

public function compileString( string $viewCode, bool $extendsMode = bool ): string;
将模板编译成字符串

echo $compiler->compileString({% raw %}'{{ "hello world" }}'{% endraw %});

public function compileSwitch( array $statement, bool $extendsMode = bool ): string;
编译一个返回 PHP 代码的 'switch' 语句

final public function expression( array $expr, bool $doubleQuotes = bool ): string;
解析 AST volt 树中的表达式节点

final public function fireExtensionEvent( string $name, array $arguments = [] );
向已注册的扩展触发一个事件

public function functionCall( array $expr, bool $doubleQuotes = bool ): string;
将函数中间代码解析为 PHP 函数调用

public function getCompiledTemplatePath(): string;
返回最近编译的模板路径

public function getDI(): DiInterface;
返回内部的依赖注入器

public function getExtensions(): array;
返回在 Volt 中注册的扩展列表

public function getFilters(): array;
注册用户注册的过滤器

public function getFunctions(): array;
注册用户注册的函数

public function getOption( string $option ): string | null;
返回一个编译器的选项

public function getOptions(): array;
返回编译器选项

public function getTemplatePath(): string;
返回当前正在编译的路径

public function getUniquePrefix(): string;
返回一个唯一的前缀,用作编译变量和上下文的前缀

public function parse( string $viewCode ): array;
解析 Volt 模板并返回其中间表示

print_r(
    $compiler->parse("{% raw %}{{ 3 + 2 }}{% endraw %}")
);

public function resolveTest( array $test, string $left ): string;
将过滤器中间代码解析为有效的 PHP 表达式

public function setDI( DiInterface $container ): void;
设置依赖注入器

public function setOption( string $option, mixed $value );
设置单个编译器选项

public function setOptions( array $options );
设置编译器选项

public function setUniquePrefix( string $prefix ): Compiler;
设置一个唯一的前缀,用作编译变量的前缀

protected function compileSource( string $viewCode, bool $extendsMode = bool ): array | string;
编译一个 Volt 源代码并返回一个普通 PHP 版本

protected function getFinalPath( string $path );
获取带有 VIEW 的最终路径

final protected function resolveFilter( array $filter, string $left ): string;
将过滤器中间代码解析为 PHP 函数调用

final protected function statementList( array $statements, bool $extendsMode = bool ): string;
遍历一个语句列表并编译每个节点

final protected function statementListOrExtends( mixed $statements );
编译一个语句块

Mvc\View\Engine\Volt\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\View\Engine\Volt
  • 使用

    • Phalcon\Mvc\View\Exception
  • 继承

    BaseException

  • 实现

Phalcon\Mvc\View 抛出异常的类

属性

/**
 * @var array
 */
protected $statement;

方法

public function __construct( string $message = string, array $statement = [], int $code = int, \Exception $previous = null );

public function getStatement(): array;
获取当前解析的语句(如果有的话)

Mvc\View\Exception

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc\View
  • 使用

  • 继承

    \Exception

  • 实现

Phalcon\Mvc\View\Exception

Phalcon\Mvc\View 抛出异常的类

Mvc\View\Simple

GitHub上的源码

  • 命名空间

    • 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;

方法

public function __construct( array $options = [] );
Phalcon\Mvc\View\Simple 构造函数

public function __get( string $key ): mixed | null;
魔术方法,用于检索传递给视图的变量

echo $this->view->products;

public function __set( string $key, mixed $value ): void;
魔术方法,用于将变量传递给视图

$this->view->products = $products;

public function getActiveRenderPath(): string;
返回当前渲染视图的路径

public function getContent(): string;
返回另一个视图阶段的输出

public function getEventsManager(): ManagerInterface | null;
返回内部事件管理器

public function getParamsToView(): array;
返回传递给视图的参数

public function getRegisteredEngines(): array;

public function getVar( string $key ): mixed | null;
返回之前在视图中设置的参数

public function getViewsDir(): string;
获取视图目录

public function partial( string $partialPath, mixed $params = null ): void;
渲染一个局部视图

// Show a partial inside another view
$this->partial("shared/footer");
// Show a partial inside another view with parameters
$this->partial(
    "shared/footer",
    [
        "content" => $html,
    ]
);

public function registerEngines( array $engines ): void;
注册模板引擎

$this->view->registerEngines(
    [
        ".phtml" => \Phalcon\Mvc\View\Engine\Php::class,
        ".volt"  => \Phalcon\Mvc\View\Engine\Volt::class,
        ".mhtml" => \MyCustomEngine::class,
    ]
);

public function render( string $path, array $params = [] ): string;
渲染一个视图

public function setContent( string $content ): Simple;
外部设置视图内容

$this->view->setContent("<h1>hello</h1>");

public function setEventsManager( ManagerInterface $eventsManager ): void;
设置事件管理器

public function setParamToView( string $key, mixed $value ): Simple;
向视图添加参数(setVar 的别名)

$this->view->setParamToView("products", $products);

public function setVar( string $key, mixed $value ): Simple;
设置单个视图参数

$this->view->setVar("products", $products);

public function setVars( array $params, bool $merge = bool ): Simple;
设置所有渲染参数

$this->view->setVars(
    [
        "products" => $products,
    ]
);

public function setViewsDir( string $viewsDir ): void;
设置视图目录

final protected function internalRender( string $path, mixed $params ): void;
尝试使用组件中注册的每一个引擎来渲染视图

protected function loadTemplateEngines(): array;
加载已注册的模板引擎,如果没有注册则会使用 Phalcon\Mvc\View\Engine\Php

Mvc\ViewBaseInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc
  • 使用

    • Phalcon\Cache\Adapter\AdapterInterface
  • 继承

  • 实现

Phalcon\Mvc\ViewInterface

Phalcon\Mvc\View 和 Phalcon\Mvc\View\Simple 的接口

方法

public function getContent(): string;
返回来自其他视图阶段的缓存输出

public function getParamsToView(): array;
返回传递给视图的参数

public function getViewsDir(): string | array;
获取视图目录

public function partial( string $partialPath, mixed $params = null );
渲染一个局部视图

public function setContent( string $content );
外部设置视图内容

public function setParamToView( string $key, mixed $value );
向视图添加参数(setVar 的别名)

public function setVar( string $key, mixed $value );
向视图添加参数

public function setViewsDir( string $viewsDir );
设置视图目录。根据您的平台,始终添加一个尾随斜杠或反斜杠

Mvc\ViewInterfaceInterface

GitHub上的源码

  • 命名空间

    • Phalcon\Mvc
  • 使用

  • 继承

    ViewBaseInterface

  • 实现

Phalcon\Mvc\ViewInterface

Phalcon\Mvc\View 接口

方法

public function cleanTemplateAfter();
重置所有“before”模板布局

public function cleanTemplateBefore();
重置所有“before”模板布局

public function disable();
禁用自动渲染进程

public function enable();
启用自动渲染进程

public function finish();
通过停止输出缓冲结束渲染过程

public function getActionName(): string;
获取已渲染动作的名称

public function getActiveRenderPath(): string | array;
返回当前渲染视图的路径

public function getBasePath(): string;
获取基础路径

public function getControllerName(): string;
获取已渲染控制器的名称

public function getLayout(): string;
返回主视图的名称

public function getLayoutsDir(): string;
获取当前布局子目录

public function getMainView(): string;
返回主视图的名称

public function getPartialsDir(): string;
获取当前局部视图子目录

public function isDisabled(): bool;
是否禁用了自动渲染

public function pick( string $renderView );
选择与上一个控制器/动作不同的视图进行渲染

public function registerEngines( array $engines );
注册模板引擎

public function render( string $controllerName, string $actionName, array $params = [] ): ViewInterface | bool;
从分发的数据开始执行渲染过程

public function reset();
将视图组件重置为出厂默认值

public function setBasePath( string $basePath );
设置基础路径。根据您的平台,始终添加一个尾随斜杠或反斜杠

public function setLayout( string $layout );
更改使用的布局,而不是使用最新控制器的名称

public function setLayoutsDir( string $layoutsDir );
设置布局子目录。必须是位于视图目录下的目录。根据您的平台,始终添加一个尾随斜杠或反斜杠

public function setMainView( string $viewPath );
设置默认视图名称。它必须是一个没有扩展名的文件,并且位于视图目录下

public function setPartialsDir( string $partialsDir );
设置局部视图子目录。必须是位于视图目录下的目录。根据您的平台,始终添加一个尾随斜杠或反斜杠

public function setRenderLevel( int $level ): ViewInterface;
设置视图的渲染层级

public function setTemplateAfter( mixed $templateAfter );
在控制器布局之后追加模板

public function setTemplateBefore( mixed $templateBefore );
在控制器布局之前追加模板

public function start();
开始渲染过程并启用输出缓冲

无噪 Logo
无噪文档
25 年 6 月翻译
版本号 5.9
文档源↗