gpt4 book ai didi

php - 扩展 PHP 类以允许通过 __callStatic 找到新方法

转载 作者:行者123 更新时间:2023-12-04 16:55:29 26 4
gpt4 key购买 nike

寻找一种灵活的方式来允许其他开发人员为模板系统扩展渲染方法,基本上允许他们生成自己的 render::whatever([ 'params' ]) 方法。
从单个开发人员的角度来看,当前的设置运行良好,我有许多基于上下文(帖子、媒体、分类法等)的类设置,带有 __callStatic收集检查是否method_exists的调用函数的方法在类中,如果是,则提取任何传递的参数并呈现输出。
快速示例(伪代码):
-- View /page.php

render::title('<div>{{ title }}</div>');
-- app/render.php
class render {

public static function __callStatic( $function, $args ) {

// check if method exists
if ( method_exists( __CLASS__, $function ){

self::{ $function }( $args );

}

}

public static function title( $args ) {

// do something with the passed args...

}

}
我想允许开发人员从他们自己包含的类中扩展可用的方法 - 这样他们就可以创建例如 render::date( $args );并将其传递给他们的逻辑以收集数据,然后将结果呈现给模板。
问题是,哪种方法最有效并且性能好——错误是安全性在这一点上不是一个大问题,以后可能会出现。
编辑 -
我已经通过执行以下操作(再次伪代码..)来完成这项工作:
-- app/render.php
class render {

public static function __callStatic( $function, $args ) {

// check if method exists
if (
method_exists( __CLASS__, $function
){

self::{ $function }( $args );

}

// check if method exists in extended class
if (
method_exists( __CLASS__.'_extend', $function
){

__CLASS__.'_extend'::{ $function }( $args );

}

}

public static function title( $args ) {

// do something with the passed args...

}

}
-- child_app/render_extend.php
class render_extend {

public static function date( $args = null ) {

// do some dating..

}

}
这里的问题是这仅限于基础 render() 类的一个扩展。

最佳答案

一种常见的方法(由 Twig 和 Smarty 用于几个示例)是要求开发人员手动将其扩展注册为可调用对象。 render class 保留它们的记录,然后除了检查它自己的内部方法之外,还检查来自 _callStatic 的这个列表。 .
根据您已有的内容,这可能如下所示:

class render
{
/** @var array */
private static $extensions;

public static function __callStatic($function, $args)
{
// check if method exists in class methods...
if ( method_exists( __CLASS__, $function )) {
self::{$function}(self::$args);
}
// and also in registry
elseif (isset(self::$extensions[$function])) {
(self::$extensions[$function])($args);
}
}

public static function title($args)
{
// do something with the passed args...
}

public static function register(string $name, callable $callback)
{
self::$extensions[$name] = $callback;
}
}
开发人员会像这样使用它:
render::register('date', function($args) {
// Do something to do with dates
});
完整演示在这里: https://3v4l.org/oOiN6

关于php - 扩展 PHP 类以允许通过 __callStatic 找到新方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62615843/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com