洛丽糖
洛丽糖(luolt.cn),致力于互联网资源的共享, 分享各类技术教程,typecho主题模板,zblog主题模板,网站源码等各种资源。
avatar
1279 文章 1476 评论 4 分类 8 页面
使用AI写的“Component”类,一个功能丰富的 PHP 组件基类。(未验证是否用)
寻梦xunm| 74| 日常生活
21天前
(未验证是否用)Component 是一个功能丰富的 PHP 组件基类,提供了完整的属性管理、事件系统、验证机制和渲染功能。它采用面向对象设计,支持继承和扩展,可用于构建各种 UI 组件。
<?php
/**
 * 丰富的 PHP 组件基类
 * 提供属性管理、事件系统、验证机制和渲染功能
 */
class Component
{
    // 组件配置
    private $_config = [];
    
    // 事件处理器
    private $_events = [];
    
    // 验证规则
    private $_rules = [];
    
    // 验证错误信息
    private $_errors = [];
    
    // 组件标签
    protected $tag = 'div';
    
    // 组件内容
    protected $content = '';
    
    // 默认配置
    protected $defaultConfig = [
        'id' => null,
        'class' => '',
        'style' => '',
        'attributes' => [],
        'visible' => true,
        'enabled' => true
    ];
    
    /**
     * 构造函数
     * @param array $config 组件配置
     */
    public function __construct($config = [])
    {
        // 合并默认配置
        $this->_config = array_merge($this->defaultConfig, $config);
        
        // 如果没有ID,自动生成
        if (empty($this->_config['id'])) {
            $this->_config['id'] = $this->generateId();
        }
        
        // 初始化
        $this->init();
    }
    
    /**
     * 初始化方法,子类可重写
     */
    protected function init()
    {
        // 子类可重写此方法进行初始化
    }
    
    /**
     * 获取组件ID
     * @return string
     */
    public function getId()
    {
        return $this->_config['id'];
    }
    
    /**
     * 设置组件ID
     * @param string $id
     */
    public function setId($id)
    {
        $this->_config['id'] = $id;
    }
    
    /**
     * 获取配置值
     * @param string $name 配置名
     * @param mixed $default 默认值
     * @return mixed
     */
    public function getConfig($name, $default = null)
    {
        return isset($this->_config[$name]) ? $this->_config[$name] : $default;
    }
    
    /**
     * 设置配置值
     * @param string|array $name 配置名或配置数组
     * @param mixed $value 配置值
     */
    public function setConfig($name, $value = null)
    {
        if (is_array($name)) {
            $this->_config = array_merge($this->_config, $name);
        } else {
            $this->_config[$name] = $value;
        }
    }
    
    /**
     * 获取属性值
     * @param string $name 属性名
     * @param mixed $default 默认值
     * @return mixed
     */
    public function __get($name)
    {
        // 检查配置中是否存在
        if (isset($this->_config[$name])) {
            return $this->_config[$name];
        }
        
        // 检查是否有getter方法
        $getter = 'get' . ucfirst($name);
        if (method_exists($this, $getter)) {
            return $this->$getter();
        }
        
        // 抛出异常
        throw new Exception("获取未定义的属性: " . get_class($this) . "::{$name}");
    }
    
    /**
     * 设置属性值
     * @param string $name 属性名
     * @param mixed $value 属性值
     */
    public function __set($name, $value)
    {
        // 检查是否有setter方法
        $setter = 'set' . ucfirst($name);
        if (method_exists($this, $setter)) {
            $this->$setter($value);
            return;
        }
        
        // 直接设置到配置中
        $this->_config[$name] = $value;
    }
    
    /**
     * 检查属性是否存在
     * @param string $name 属性名
     * @return bool
     */
    public function __isset($name)
    {
        return isset($this->_config[$name]) || method_exists($this, 'get' . ucfirst($name));
    }
    
    /**
     * 绑定事件处理器
     * @param string $event 事件名
     * @param callable $handler 事件处理器
     * @param mixed $data 传递给事件处理器的数据
     */
    public function on($event, $handler, $data = null)
    {
        $this->_events[$event][] = [$handler, $data];
    }
    
    /**
     * 解除事件绑定
     * @param string $event 事件名
     * @param callable $handler 事件处理器
     * @return bool 是否成功解除
     */
    public function off($event, $handler = null)
    {
        if (empty($this->_events[$event])) {
            return false;
        }
        
        if ($handler === null) {
            unset($this->_events[$event]);
            return true;
        }
        
        $removed = false;
        foreach ($this->_events[$event] as $key => $eventHandler) {
            if ($eventHandler[0] === $handler) {
                unset($this->_events[$event][$key]);
                $removed = true;
            }
        }
        
        if ($removed) {
            $this->_events[$event] = array_values($this->_events[$event]);
        }
        
        return $removed;
    }
    
    /**
     * 触发事件
     * @param string $event 事件名
     * @param mixed $eventData 事件数据
     * @return bool 是否继续执行
     */
    public function trigger($event, $eventData = null)
    {
        if (empty($this->_events[$event])) {
            return true;
        }
        
        foreach ($this->_events[$event] as $handler) {
            list($callback, $data) = $handler;
            
            // 合并数据
            $finalData = $eventData;
            if ($data !== null) {
                $finalData = array_merge([$eventData], (array)$data);
            }
            
            // 调用处理器
            if (call_user_func($callback, $finalData, $this) === false) {
                return false; // 停止事件传播
            }
        }
        
        return true;
    }
    
    /**
     * 添加验证规则
     * @param string $attribute 属性名
     * @param mixed $validator 验证器
     * @param array $options 选项
     */
    public function addRule($attribute, $validator, $options = [])
    {
        $this->_rules[$attribute][] = [
            'validator' => $validator,
            'options' => $options
        ];
    }
    
    /**
     * 验证数据
     * @param array $data 待验证的数据
     * @return bool 是否验证通过
     */
    public function validate($data = null)
    {
        $this->_errors = [];
        
        if ($data === null) {
            $data = $this->_config;
        }
        
        foreach ($this->_rules as $attribute => $rules) {
            $value = isset($data[$attribute]) ? $data[$attribute] : null;
            
            foreach ($rules as $rule) {
                $validator = $rule['validator'];
                $options = $rule['options'];
                
                if (!$this->validateValue($value, $validator, $options)) {
                    $message = isset($options['message']) ? $options['message'] : "{$attribute} 验证失败";
                    $this->addError($attribute, $message);
                    break;
                }
            }
        }
        
        return empty($this->_errors);
    }
    
    /**
     * 验证单个值
     * @param mixed $value 值
     * @param mixed $validator 验证器
     * @param array $options 选项
     * @return bool
     */
    protected function validateValue($value, $validator, $options)
    {
        if (is_string($validator)) {
            switch ($validator) {
                case 'required':
                    return !empty($value) || $value === 0 || $value === '0';
                case 'email':
                    return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
                case 'url':
                    return filter_var($value, FILTER_VALIDATE_URL) !== false;
                case 'numeric':
                    return is_numeric($value);
                case 'integer':
                    return filter_var($value, FILTER_VALIDATE_INT) !== false;
                default:
                    // 支持正则表达式
                    if (substr($validator, 0, 1) === '/') {
                        return preg_match($validator, $value) === 1;
                    }
                    return true;
            }
        } elseif (is_callable($validator)) {
            return call_user_func($validator, $value, $options);
        }
        
        return true;
    }
    
    /**
     * 添加错误信息
     * @param string $attribute 属性名
     * @param string $message 错误信息
     */
    public function addError($attribute, $message)
    {
        $this->_errors[$attribute][] = $message;
    }
    
    /**
     * 获取错误信息
     * @param string $attribute 属性名
     * @return array
     */
    public function getErrors($attribute = null)
    {
        if ($attribute === null) {
            return $this->_errors;
        }
        
        return isset($this->_errors[$attribute]) ? $this->_errors[$attribute] : [];
    }
    
    /**
     * 获取第一条错误信息
     * @param string $attribute 属性名
     * @return string|null
     */
    public function getFirstError($attribute = null)
    {
        if ($attribute === null) {
            foreach ($this->_errors as $errors) {
                if (!empty($errors)) {
                    return reset($errors);
                }
            }
            return null;
        }
        
        return isset($this->_errors[$attribute]) ? reset($this->_errors[$attribute]) : null;
    }
    
    /**
     * 检查是否有错误
     * @param string $attribute 属性名
     * @return bool
     */
    public function hasErrors($attribute = null)
    {
        return $attribute === null ? !empty($this->_errors) : isset($this->_errors[$attribute]);
    }
    
    /**
     * 渲染组件
     * @return string
     */
    public function render()
    {
        if (!$this->visible) {
            return '';
        }
        
        $this->trigger('beforeRender');
        
        $attributes = $this->buildAttributes();
        $content = $this->renderContent();
        
        $html = "<{$this->tag}{$attributes}>{$content}</{$this->tag}>";
        
        $this->trigger('afterRender', $html);
        
        return $html;
    }
    
    /**
     * 构建HTML属性
     * @return string
     */
    protected function buildAttributes()
    {
        $attributes = [];
        
        // 基本属性
        if (!empty($this->id)) {
            $attributes['id'] = $this->id;
        }
        
        if (!empty($this->class)) {
            $attributes['class'] = $this->class;
        }
        
        if (!empty($this->style)) {
            $attributes['style'] = $this->style;
        }
        
        // 自定义属性
        if (!empty($this->attributes) && is_array($this->attributes)) {
            $attributes = array_merge($attributes, $this->attributes);
        }
        
        // 构建属性字符串
        $parts = [];
        foreach ($attributes as $name => $value) {
            if (is_bool($value)) {
                if ($value) {
                    $parts[] = $name;
                }
            } else {
                $parts[] = $name . '="' . htmlspecialchars($value, ENT_QUOTES, 'UTF-8') . '"';
            }
        }
        
        return $parts ? ' ' . implode(' ', $parts) : '';
    }
    
    /**
     * 渲染内容
     * @return string
     */
    protected function renderContent()
    {
        return $this->content;
    }
    
    /**
     * 生成唯一ID
     * @return string
     */
    protected function generateId()
    {
        return uniqid('comp_');
    }
    
    /**
     * 魔术方法:将对象转换为字符串
     * @return string
     */
    public function __toString()
    {
        try {
            return $this->render();
        } catch (Exception $e) {
            return 'Error: ' . $e->getMessage();
        }
    }
}

/**
 * 表单输入组件示例
 */
class Input extends Component
{
    protected $tag = 'input';
    protected $defaultConfig = [
        'type' => 'text',
        'name' => '',
        'value' => '',
        'placeholder' => '',
        'required' => false,
        'maxlength' => null,
        'minlength' => null,
        'pattern' => null
    ];
    
    /**
     * 渲染内容(对于input标签,不需要内容)
     * @return string
     */
    protected function renderContent()
    {
        return '';
    }
    
    /**
     * 构建HTML属性
     * @return string
     */
    protected function buildAttributes()
    {
        // 添加input特定属性
        $this->attributes['type'] = $this->type;
        $this->attributes['name'] = $this->name;
        $this->attributes['value'] = $this->value;
        
        if (!empty($this->placeholder)) {
            $this->attributes['placeholder'] = $this->placeholder;
        }
        
        if ($this->required) {
            $this->attributes['required'] = true;
        }
        
        if (!empty($this->maxlength)) {
            $this->attributes['maxlength'] = $this->maxlength;
        }
        
        if (!empty($this->minlength)) {
            $this->attributes['minlength'] = $this->minlength;
        }
        
        if (!empty($this->pattern)) {
            $this->attributes['pattern'] = $this->pattern;
        }
        
        return parent::buildAttributes();
    }
}

/**
 * 按钮组件示例
 */
class Button extends Component
{
    protected $tag = 'button';
    protected $defaultConfig = [
        'type' => 'button',
        'text' => '按钮',
        'onclick' => ''
    ];
    
    /**
     * 渲染内容
     * @return string
     */
    protected function renderContent()
    {
        return $this->text;
    }
    
    /**
     * 构建HTML属性
     * @return string
     */
    protected function buildAttributes()
    {
        $this->attributes['type'] = $this->type;
        
        if (!empty($this->onclick)) {
            $this->attributes['onclick'] = $this->onclick;
        }
        
        return parent::buildAttributes();
    }
}

// 使用示例
echo "<h2>PHP 组件类示例</h2>";

// 创建输入框
$input = new Input([
    'name' => 'username',
    'placeholder' => '请输入用户名',
    'class' => 'form-input',
    'required' => true
]);

// 添加验证规则
$input->addRule('name', 'required', ['message' => '用户名不能为空']);
$input->addRule('value', function($value) {
    return strlen($value) >= 3;
}, ['message' => '用户名至少3个字符']);

// 测试验证
$input->value = 'ab';
if (!$input->validate()) {
    echo "<p style='color:red'>输入框验证错误: " . $input->getFirstError('value') . "</p>";
}

// 渲染输入框
echo "<p>输入框: " . $input->render() . "</p>";

// 创建按钮
$button = new Button([
    'text' => '提交',
    'type' => 'submit',
    'class' => 'btn btn-primary',
    'onclick' => 'submitForm()'
]);

// 渲染按钮
echo "<p>按钮: " . $button->render() . "</p>";

// 演示事件系统
echo "<h3>事件系统演示</h3>";

$component = new Component();
$component->on('customEvent', function($data, $sender) {
    echo "<p>自定义事件触发,数据: " . $data . "</p>";
});

$component->trigger('customEvent', 'Hello World!');

// 演示属性访问
echo "<h3>属性访问演示</h3>";
$component->setConfig('customProperty', '自定义值');
echo "<p>自定义属性值: " . $component->customProperty . "</p>";

echo "<p><strong>组件类功能丰富,包含属性管理、事件系统、验证机制和渲染功能!</strong></p>";
?>

Component 组件类完整文档

概述

Component 是一个功能丰富的 PHP 组件基类,提供了完整的属性管理、事件系统、验证机制和渲染功能。它采用面向对象设计,支持继承和扩展,可用于构建各种 UI 组件。

目录

  1. 核心特性
  2. 类结构
  3. 属性管理
  4. 事件系统
  5. 验证机制
  6. 渲染系统
  7. 继承与扩展
  8. 使用示例
  9. API 参考
  10. 最佳实践

核心特性

1. 属性管理

  • 灵活的配置系统
  • 魔术方法支持
  • 类型安全访问
  • 默认值管理

2. 事件系统

  • 事件绑定与解绑
  • 事件触发与传播
  • 数据传递支持
  • 事件链控制

3. 验证机制

  • 多种验证器类型
  • 自定义验证规则
  • 错误信息收集
  • 批量验证支持

4. 渲染系统

  • HTML 属性自动构建
  • 内容渲染模板
  • 前后事件钩子
  • 字符串化支持

类结构

Component 基类

class Component
{
    // 配置管理
    private $_config = [];
    protected $defaultConfig = [];
    
    // 事件系统
    private $_events = [];
    
    // 验证系统
    private $_rules = [];
    private $_errors = [];
    
    // 渲染系统
    protected $tag = 'div';
    protected $content = '';
}

核心方法分类

类别方法
生命周期__construct(), init()
属性访问__get(), __set(), __isset()
配置管理getConfig(), setConfig(), getId(), setId()
事件系统on(), off(), trigger()
验证系统addRule(), validate(), validateValue()
错误处理addError(), getErrors(), getFirstError(), hasErrors()
渲染系统render(), buildAttributes(), renderContent(), __toString()

属性管理

配置系统

组件使用两级配置系统:

  • defaultConfig: 默认配置(受保护)
  • $_config: 运行时配置(私有)

配置访问方式

1. 构造函数配置

$component = new Component([
    'id' => 'my-component',
    'class' => 'container',
    'visible' => true
]);

2. 配置方法访问

// 获取配置
$id = $component->getConfig('id');
$class = $component->getConfig('class', 'default-class');

// 设置配置
$component->setConfig('class', 'new-class');
$component->setConfig([
    'style' => 'color: red;',
    'enabled' => false
]);

3. 魔术方法访问

// 属性式访问
$component->id = 'new-id';
$value = $component->class;

// 检查存在性
if (isset($component->visible)) {
    // 属性存在
}

4. Getter/Setter 支持

class CustomComponent extends Component
{
    public function setCustomProperty($value)
    {
        // 自定义设置逻辑
        $this->_config['customProperty'] = $value;
    }
    
    public function getCustomProperty()
    {
        // 自定义获取逻辑
        return $this->_config['customProperty'] ?? null;
    }
}

事件系统

事件绑定

// 绑定简单事件
$component->on('click', function($data, $sender) {
    echo "组件被点击! 数据: {$data}";
});

// 绑定带参数的事件
$component->on('customEvent', function($data, $sender) {
    list($eventData, $userData) = $data;
    echo "事件数据: {$eventData}, 用户数据: {$userData}";
}, 'additional-data');

// 绑定对象方法
class EventHandler
{
    public function handleEvent($data, $sender)
    {
        // 事件处理逻辑
    }
}

$handler = new EventHandler();
$component->on('event', [$handler, 'handleEvent']);

事件触发

// 触发简单事件
$component->trigger('click', '按钮点击');

// 触发带多个参数的事件
$component->trigger('customEvent', ['主要数据', '次要数据']);

// 检查事件是否被阻止
$continue = $component->trigger('beforeAction', $data);
if ($continue) {
    // 继续执行
}

事件解绑

// 解绑特定处理器
$component->off('click', $handler);

// 解绑所有处理器
$component->off('click');

内置事件

组件预定义了以下事件:

事件触发时机参数
beforeRender渲染开始前null
afterRender渲染完成后渲染的HTML

验证机制

验证规则类型

1. 字符串验证器

// 必填验证
$component->addRule('username', 'required', [
    'message' => '用户名不能为空'
]);

// 邮箱验证
$component->addRule('email', 'email', [
    'message' => '邮箱格式不正确'
]);

// URL验证
$component->addRule('website', 'url', [
    'message' => '网址格式不正确'
]);

// 数字验证
$component->addRule('age', 'numeric', [
    'message' => '年龄必须是数字'
]);

// 整数验证
$component->addRule('count', 'integer', [
    'message' => '数量必须是整数'
]);

2. 正则表达式验证

// 手机号验证
$component->addRule('phone', '/^1[3-9]\d{9}$/', [
    'message' => '手机号格式不正确'
]);

// 用户名格式验证
$component->addRule('username', '/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/', [
    'message' => '用户名格式不正确'
]);

3. 回调函数验证

// 自定义验证函数
$component->addRule('password', function($value, $options) {
    return strlen($value) >= 6 && preg_match('/[A-Z]/', $value);
}, [
    'message' => '密码必须至少6位且包含大写字母'
]);

// 类方法验证
$component->addRule('customField', [$this, 'validateCustomField'], [
    'message' => '自定义验证失败'
]);

验证执行

// 验证当前配置
if ($component->validate()) {
    echo "验证通过";
} else {
    // 获取所有错误
    $errors = $component->getErrors();
    
    // 获取特定属性错误
    $usernameErrors = $component->getErrors('username');
    
    // 获取第一条错误
    $firstError = $component->getFirstError();
    
    // 检查是否有错误
    if ($component->hasErrors('email')) {
        // 处理邮箱错误
    }
}

验证外部数据

// 验证外部数据
$data = [
    'username' => 'test',
    'email' => 'invalid-email'
];

if ($component->validate($data)) {
    // 数据有效
} else {
    $errors = $component->getErrors();
}

渲染系统

基础渲染

// 自动渲染
echo $component;

// 手动渲染
$html = $component->render();

// 条件渲染
if ($component->visible) {
    echo $component;
}

属性构建

组件自动处理以下属性:

$component = new Component([
    'id' => 'my-id',
    'class' => 'btn btn-primary',
    'style' => 'color: red;',
    'attributes' => [
        'data-toggle' => 'modal',
        'aria-label' => 'Close'
    ]
]);

// 渲染结果: <div id="my-id" class="btn btn-primary" style="color: red;" data-toggle="modal" aria-label="Close"></div>

自定义渲染

重写渲染方法

class CustomComponent extends Component
{
    protected function renderContent()
    {
        return "<span>自定义内容</span>";
    }
    
    protected function buildAttributes()
    {
        // 添加自定义属性
        $this->attributes['custom-attr'] = 'value';
        
        // 调用父类方法
        return parent::buildAttributes();
    }
}

继承与扩展

创建表单组件

class FormInput extends Component
{
    protected $tag = 'input';
    
    protected $defaultConfig = [
        'type' => 'text',
        'name' => '',
        'value' => '',
        'placeholder' => '',
        'required' => false,
        'disabled' => false,
        'readonly' => false
    ];
    
    protected function renderContent()
    {
        return ''; // input 标签无内容
    }
    
    protected function buildAttributes()
    {
        // 设置输入框特定属性
        $this->attributes['type'] = $this->type;
        $this->attributes['name'] = $this->name;
        $this->attributes['value'] = $this->value;
        
        if ($this->placeholder) {
            $this->attributes['placeholder'] = $this->placeholder;
        }
        
        if ($this->required) {
            $this->attributes['required'] = true;
        }
        
        if ($this->disabled) {
            $this->attributes['disabled'] = true;
        }
        
        if ($this->readonly) {
            $this->attributes['readonly'] = true;
        }
        
        return parent::buildAttributes();
    }
}

创建容器组件

class Container extends Component
{
    protected $defaultConfig = [
        'children' => [],
        'direction' => 'vertical' // horizontal, vertical
    ];
    
    protected function renderContent()
    {
        $content = '';
        
        foreach ($this->children as $child) {
            if ($child instanceof Component) {
                $content .= $child->render();
            } else {
                $content .= $child;
            }
        }
        
        return $content;
    }
    
    protected function buildAttributes()
    {
        // 添加布局类
        $layoutClass = $this->direction === 'horizontal' ? 'layout-horizontal' : 'layout-vertical';
        $this->class = trim($this->class . ' ' . $layoutClass);
        
        return parent::buildAttributes();
    }
    
    public function addChild($child)
    {
        $this->children[] = $child;
        return $this;
    }
}

使用示例

完整表单示例

<?php
// 创建表单容器
$form = new Container([
    'id' => 'user-form',
    'class' => 'user-form',
    'attributes' => [
        'method' => 'POST',
        'action' => '/submit'
    ]
]);

// 创建用户名输入框
$username = new FormInput([
    'name' => 'username',
    'placeholder' => '请输入用户名',
    'required' => true
]);

// 添加验证规则
$username->addRule('value', 'required', ['message' => '用户名不能为空']);
$username->addRule('value', '/^[a-zA-Z][a-zA-Z0-9_]{3,15}$/', [
    'message' => '用户名必须为3-15位字母数字下划线,以字母开头'
]);

// 创建邮箱输入框
$email = new FormInput([
    'type' => 'email',
    'name' => 'email',
    'placeholder' => '请输入邮箱'
]);

$email->addRule('value', 'email', ['message' => '邮箱格式不正确']);

// 创建密码输入框
$password = new FormInput([
    'type' => 'password',
    'name' => 'password',
    'placeholder' => '请输入密码'
]);

$password->addRule('value', function($value) {
    return strlen($value) >= 6;
}, ['message' => '密码至少6位']);

// 创建提交按钮
$submit = new Button([
    'type' => 'submit',
    'text' => '注册',
    'class' => 'btn btn-primary'
]);

// 添加事件
$submit->on('click', function() {
    echo "表单提交中...";
});

// 组装表单
$form->addChild($username);
$form->addChild($email);
$form->addChild($password);
$form->addChild($submit);

// 渲染表单
echo $form;
?>

动态组件管理

<?php
// 组件工厂
class ComponentFactory
{
    public static function createButton($text, $type = 'button', $options = [])
    {
        return new Button(array_merge([
            'text' => $text,
            'type' => $type,
            'class' => 'btn'
        ], $options));
    }
    
    public static function createInput($name, $type = 'text', $options = [])
    {
        return new FormInput(array_merge([
            'name' => $name,
            'type' => $type,
            'class' => 'form-control'
        ], $options));
    }
}

// 使用工厂创建组件
$buttons = [
    ComponentFactory::createButton('保存', 'submit', ['class' => 'btn-success']),
    ComponentFactory::createButton('取消', 'button', ['class' => 'btn-secondary'])
];

$container = new Container(['class' => 'button-group']);
foreach ($buttons as $button) {
    $container->addChild($button);
}

echo $container;
?>

API 参考

公共方法

__construct($config = [])

构造函数,初始化组件配置。

参数:

  • $config (array) - 组件配置数组

示例:

$component = new Component(['id' => 'test', 'class' => 'container']);

getId()

获取组件ID。

返回: string

setId($id)

设置组件ID。

参数:

  • $id (string) - 组件ID

getConfig($name, $default = null)

获取配置值。

参数:

  • $name (string) - 配置名
  • $default (mixed) - 默认值

返回: mixed

setConfig($name, $value = null)

设置配置值。

参数:

  • $name (string|array) - 配置名或配置数组
  • $value (mixed) - 配置值(当$name为字符串时)

on($event, $handler, $data = null)

绑定事件处理器。

参数:

  • $event (string) - 事件名
  • $handler (callable) - 事件处理器
  • $data (mixed) - 传递给处理器的数据

off($event, $handler = null)

解除事件绑定。

参数:

  • $event (string) - 事件名
  • $handler (callable) - 事件处理器(可选)

返回: bool

trigger($event, $eventData = null)

触发事件。

参数:

  • $event (string) - 事件名
  • $eventData (mixed) - 事件数据

返回: bool

addRule($attribute, $validator, $options = [])

添加验证规则。

参数:

  • $attribute (string) - 属性名
  • $validator (string|callable) - 验证器
  • $options (array) - 验证选项

validate($data = null)

验证数据。

参数:

  • $data (array) - 待验证数据(可选)

返回: bool

getErrors($attribute = null)

获取错误信息。

参数:

  • $attribute (string) - 属性名(可选)

返回: array

getFirstError($attribute = null)

获取第一条错误信息。

参数:

  • $attribute (string) - 属性名(可选)

返回: string|null

hasErrors($attribute = null)

检查是否有错误。

参数:

  • $attribute (string) - 属性名(可选)

返回: bool

render()

渲染组件。

返回: string

__toString()

将组件转换为字符串。

返回: string

受保护方法

init()

初始化方法,子类可重写。

validateValue($value, $validator, $options)

验证单个值。

参数:

  • $value (mixed) - 待验证值
  • $validator (string|callable) - 验证器
  • $options (array) - 验证选项

返回: bool

addError($attribute, $message)

添加错误信息。

参数:

  • $attribute (string) - 属性名
  • $message (string) - 错误信息

buildAttributes()

构建HTML属性字符串。

返回: string

renderContent()

渲染组件内容。

返回: string

generateId()

生成唯一ID。

返回: string

最佳实践

1. 组件设计原则

单一职责

// 好的设计:每个组件职责单一
class TextInput extends Component { /* 处理文本输入 */ }
class NumberInput extends Component { /* 处理数字输入 */ }
class DateInput extends Component { /* 处理日期输入 */ }

// 不好的设计:一个组件处理所有输入类型
class UniversalInput extends Component { /* 处理所有输入类型,逻辑复杂 */ }

开放封闭

// 通过继承扩展功能,而不是修改基类
class AdvancedInput extends FormInput
{
    protected function buildAttributes()
    {
        // 添加新功能而不修改父类
        $this->attributes['data-advanced'] = 'true';
        return parent::buildAttributes();
    }
}

2. 性能优化

批量配置

// 好的做法:一次性设置所有配置
$component->setConfig([
    'id' => 'test',
    'class' => 'container',
    'style' => 'color: red;'
]);

// 不好的做法:多次设置
$component->setConfig('id', 'test');
$component->setConfig('class', 'container');
$component->setConfig('style', 'color: red;');

事件管理

// 及时清理不需要的事件处理器
class DynamicComponent extends Component
{
    public function cleanup()
    {
        // 清理所有事件
        $this->off('click');
        $this->off('customEvent');
    }
}

3. 错误处理

友好的错误信息

// 提供具体的错误信息
$component->addRule('email', 'email', [
    'message' => '请输入有效的邮箱地址,例如:user@example.com'
]);

// 使用上下文相关的错误信息
$component->addRule('age', 'integer', [
    'message' => function($value, $options) {
        return "年龄必须是整数,当前值:{$value}";
    }
]);

4. 安全性

HTML 转义

class SafeComponent extends Component
{
    protected function buildAttributes()
    {
        // 确保所有属性值都经过转义
        $parts = [];
        foreach ($this->attributes as $name => $value) {
            $escapedValue = htmlspecialchars($value, ENT_QUOTES, 'UTF-8');
            $parts[] = "{$name}=\"{$escapedValue}\"";
        }
        return $parts ? ' ' . implode(' ', $parts) : '';
    }
}

扩展建议

1. 添加模板引擎支持

class TemplateComponent extends Component
{
    protected $template = '';
    
    public function setTemplate($template)
    {
        $this->template = $template;
        return $this;
    }
    
    protected function renderContent()
    {
        if ($this->template) {
            return $this->renderTemplate();
        }
        return parent::renderContent();
    }
    
    protected function renderTemplate()
    {
        // 简单的模板变量替换
        $content = $this->template;
        foreach ($this->_config as $key => $value) {
            $content = str_replace("{{{$key}}}", $value, $content);
        }
        return $content;
    }
}

2. 添加数据绑定

class DataBoundComponent extends Component
{
    protected $data = [];
    
    public function bind($data)
    {
        $this->data = $data;
        return $this;
    }
    
    public function getBoundValue($key, $default = null)
    {
        return $this->data[$key] ?? $default;
    }
}

总结

Component 类提供了一个强大而灵活的组件系统基础,具有以下优势:

  1. 易用性:简单的 API 设计,直观的属性访问
  2. 扩展性:良好的继承体系,支持自定义组件
  3. 功能性:完整的事件系统、验证机制和渲染功能
  4. 健壮性:完善的错误处理和验证机制
  5. 灵活性:支持多种配置方式和自定义行为

通过合理使用和扩展 Component 类,可以构建出复杂而维护性良好的 PHP 组件系统。

0 赞 or 打赏
喜欢就打赏一点
微信 支付宝
站内搜索
Q Q:1340326824
邮箱:vipshiyi@qq.com
QQ群:422720328
本站没得会员制度,所有资源都有白嫖的方法,且用且珍惜! 本站相关资源来自互联网用户收集发布,仅供用于学习和交流。 如有侵权之处,请联系站长并出示相关证明以便删除,敬请谅解!

我的音乐