讲师中心 微信公众号
AI工具推荐 视频效率加速

使用特征、接口和抽象类增强面向对象的设计

胖婷大大_8319

胖婷大大_8319

发布时间:2024-07-30 09:19:31

|

491人浏览过

|

来源于dev.to

转载

使用特征、接口和抽象类增强面向对象的设计

在面向对象编程中,保持简洁和模块化设计对于创建可扩展和可维护的应用程序至关重要。通过利用设计模式和原则,开发人员可以创建灵活且易于扩展的代码。本文探讨了如何使用特征、接口和抽象类来增强您的设计,重点关注数据传输对象 (dto) 作为实际示例。

了解基础知识:特征、接口和抽象类

特质:
traits 是 php 等单继承语言中代码重用的机制。它们允许您定义可在多个类中使用的方法,从而促进代码重用,而无需继承。

接口:
接口定义了类必须遵守的契约。它们指定类必须实现哪些方法,确保一致性并允许多态性。

抽象类:
抽象类提供了其他类可以扩展的基类。它们可以包括抽象方法(必须由子类实现)和具体方法(可以按原样使用或重写)。

实际示例:在 dto 中实现特征、接口和抽象类

为了说明特征、接口和抽象类如何协同工作,让我们使用数据传输对象 (dto) 的示例。 dto 用于在应用程序的不同层之间传输数据,而不包含业务逻辑。我们将利用这些面向对象的原则创建一个灵活且可维护的 dto 系统。

1. 定义抽象基类

basedto 抽象类为所有 dto 提供通用功能,例如将数据转换为数组或 json 格式以及从数组初始化。

app/dto/basedto.php

namespace app\dto;

/**
 * abstract class basedto
 * 
 * provides common functionality for data transfer objects (dtos).
 */
abstract class basedto
{
    /**
     * basedto constructor.
     *
     * @param array $data initial data to populate the dto.
     */
    public function __construct(array $data = [])
    {
        $this->setfromarray($data);
    }

    /**
     * convert the dto to an array.
     *
     * @return array the dto as an associative array.
     */
    public function toarray(): array
    {
        $properties = get_object_vars($this);
        return array_filter($properties, function ($property) {
            return $property !== null;
        });
    }

    /**
     * convert the dto to a json string.
     *
     * @return string the dto as a json string.
     */
    public function tojson(): string
    {
        return json_encode($this->toarray());
    }

    /**
     * set the dto properties from an array.
     *
     * @param array $data the data to set on the dto.
     */
    protected function setfromarray(array $data): void
    {
        foreach ($data as $key => $value) {
            if (property_exists($this, $key)) {
                $this->$key = $value;
            }
        }
    }
}
2. 创建特定接口

接口定义了我们的dto根据不同的数据源(例如模型、api、csv文件)需要实现的具体方法。

app/contracts/dto/setfrommodel.php

/**
 * interface setfrommodel
 * 
 * defines a method for setting dto properties from a model.
 */
interface setfrommodel
{
    /**
     * set dto properties from a model.
     *
     * @param mixed $model the model to set properties from.
     * @return self
     */
    public function setfrommodel($model): self;
}

app/contracts/dto/setfromapi.php

/**
 * interface setfromapi
 * 
 * defines a method for setting dto properties from api data.
 */
interface setfromapi
{
    /**
     * set dto properties from api data.
     *
     * @param array $data the api data to set properties from.
     * @return self
     */
    public function setfromapi(array $data): self;
}

app/contracts/dto/setfromcsv.php

/**
 * interface setfromcsv
 * 
 * defines a method for setting dto properties from csv data.
 */
interface setfromcsv
{
    /**
     * set dto properties from csv data.
     *
     * @param array $data the csv data to set properties from.
     * @return self
     */
    public function setfromcsv(array $data): self;
}
3. 实现可重用性特征

traits 允许我们定义可重用的方法来设置来自不同来源的数据,从而可以轻松地在不同的 dto 之间共享功能。

app/traits/dto/setfrommodeltrait.php

namespace app\traits\dto;

trait setfrommodeltrait
{
    public function setfrommodel($model): self
    {
        foreach (get_object_vars($model) as $key => $value) {
            if (property_exists($this, $key)) {
                $this->$key = $value;
            }
        }

        return $this;
    }
}

app/traits/dto/setfromapitrait.php

namespace app\traits\dto;

/**
 * trait setfrommodeltrait
 * 
 * provides a method for setting dto properties from a model.
 */
trait setfrommodeltrait
{
    /**
     * set dto properties from a model.
     *
     * @param mixed $model the model to set properties from.
     * @return self
     */
    public function setfrommodel($model): self
    {
        foreach (get_object_vars($model) as $key => $value) {
            if (property_exists($this, $key)) {
                $this->$key = $value;
            }
        }

        return $this;
    }
}

app/traits/dto/setfromcsvtrait.php

namespace app\traits\dto;

/**
 * trait setfromcsvtrait
 * 
 * provides a method for setting dto properties from csv data.
 */
trait setfromcsvtrait
{
    /**
     * set dto properties from csv data.
     *
     * @param array $data the csv data to set properties from.
     * @return self
     */
    public function setfromcsv(array $data): self
    {
        // assuming csv data follows a specific structure
        $this->name = $data[0] ?? null;
        $this->address = $data[1] ?? null;
        $this->price = isset($data[2]) ? (float)$data[2] : null;
        $this->subscription = $data[3] ?? null;
        $this->assets = isset($data[4]) ? explode(',', $data[4]) : [];

        return $this;
    }
}
4. 实现具体的dto类

最后,实现利用抽象类、接口和特征的具体 propertydto 类。

namespace App\DTO;

use App\Contracts\SetFromModel;
use App\Contracts\SetFromAPI;
use App\Contracts\SetFromCSV;
use App\DTO\Traits\SetFromModelTrait;
use App\DTO\Traits\SetFromAPITrait;
use App\DTO\Traits\SetFromCSVTrait;

/**
 * Class PropertyDTO
 * 
 * Represents a Property Data Transfer Object.
 */
readonly class PropertyDTO extends BaseDTO implements SetFromModel, SetFromAPI, SetFromCSV
{
    use SetFromModelTrait, SetFromAPITrait, SetFromCSVTrait;

    /**
     * @var string The name of the property.
     */
    public string $name;

    /**
     * @var string The address of the property.
     */
    public string $address;

    /**
     * @var float The price of the property.
     */
    public float $price;

    /**
     * @var ?string The subscription type of the property.
     */
    public ?string $subscription;

    /**
     * @var ?array The assets of the property.
     */
    public ?array $assets;

    // Other specific methods can be added here
}

使用特征、接口和抽象类的最佳实践

  1. 行为封装:使用traits封装常见的行为,可以跨多个类复用,减少重复,提高可维护性。

  2. 定义清晰的契约:接口应该为类必须实现的方法定义清晰的契约,确保一致性并允许轻松交换实现。

  3. 提供基础功能:抽象类提供共享功能的基础,允许子类根据需要进行扩展和自定义,同时保持通用结构。

  4. 增强灵活性:结合这些技术可以实现灵活的设计,其中类可以仅实现必要的接口并使用相关特征,从而更容易扩展和调整代码。

  5. 保持一致性:通过使用抽象类和特征,您可以确保代码保持一致并遵循可预测的模式,这对于长期可维护性至关重要。

结论

将特征、接口和抽象类集成到您的设计中提供了一种管理和构建代码的强大方法。通过应用这些原则,您可以创建一个模块化、可维护且可扩展的系统,该系统遵循面向对象编程的最佳实践。无论您使用 dto 还是其他组件,利用这些技术都有助于确保您的代码库保持干净且适应性强。

最后的想法

采用面向对象的原则和模式,例如特征、接口和抽象类,不仅可以提高代码质量,还可以增强管理复杂系统的能力。通过理解和应用这些概念,您可以构建既灵活又可维护的强大应用程序。

热门AI工具

更多
DeepSeek

DeepSeek是一款面向对话、写作、编程和推理场景的AI大模型工具。

AionClaw
AionClaw Hot

AionClaw是一款面向办公、创作和编程任务的AI桌面智能体。

音述AI
音述AI Hot

一款AI音频处理工具,主要用于音述AI是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区,适合需要提升相关任务效率的用户。

UpDream
UpDream Hot

一款AI视频创作工具,主要用于哔哩哔哩推出的自研AI视频创作工具,适合需要提升相关任务效率的用户。

VibeKnow
VibeKnow Hot

一款AI视频创作工具,主要用于全球首个AI知识视频创作平台,文档、文章、网页,一键生成视频,适合需要提升相关任务效率的用户。

Seko
Seko Hot

一款AI视频创作工具,主要用于商汤科技推出的创编一体的AI短视频创作Agent,适合需要提升相关任务效率的用户。

豆包大模型

豆包大模型是一款由字节跳动推出的企业级大语言模型服务平台。

WorkBuddy

一款AI办公效率工具,主要用于腾讯云推出的AI原生桌面智能体工作台,适合需要提升相关任务效率的用户。

超级简历WonderCV

一款AI办公效率工具,主要用于免费求职简历模版下载制作,应届生职场人必备简历制作神器,适合需要提升相关任务效率的用户。

相关专题

更多
json数据格式
json数据格式

JSON是一种轻量级的数据交换格式。本专题为大家带来json数据格式相关文章,帮助大家解决问题。

1975

2023.08.07

json是什么
json是什么

JSON是一种轻量级的数据交换格式,具有简洁、易读、跨平台和语言的特点,JSON数据是通过键值对的方式进行组织,其中键是字符串,值可以是字符串、数值、布尔值、数组、对象或者null,在Web开发、数据交换和配置文件等方面得到广泛应用。本专题为大家提供json相关的文章、下载、课程内容,供大家免费下载体验。

2702

2023.08.23

jquery怎么操作json
jquery怎么操作json

操作的方法有:1、“$.parseJSON(jsonString)”2、“$.getJSON(url, data, success)”;3、“$.each(obj, callback)”;4、“$.ajax()”。更多jquery怎么操作json的详细内容,可以访问本专题下面的文章。

936

2023.10.13

go语言处理json数据方法
go语言处理json数据方法

本专题整合了go语言中处理json数据方法,阅读专题下面的文章了解更多详细内容。

2999

2025.09.10

go语言 面向对象
go语言 面向对象

本专题整合了go语言面向对象相关内容,阅读专题下面的文章了解更多详细内容。

5255

2025.09.05

java面向对象
java面向对象

本专题整合了java面向对象相关内容,阅读专题下面的文章了解更多详细内容。

302

2025.11.27

C++ 面向对象编程与设计模式实践
C++ 面向对象编程与设计模式实践

本专题整合了 C++ 面向对象编程的核心机制,涵盖类的定义与访问控制、构造函数与析构函数、拷贝语义与移动语义、继承与虚函数多态、抽象类与接口、运算符重载、友元函数等关键知识点,同时结合单例模式、工厂模式、观察者模式、策略模式等常用设计模式的 C++ 实现,帮助开发者写出结构清晰、易于维护的面向对象代码。

304

2026.04.09

Java 面向对象与核心编程机制
Java 面向对象与核心编程机制

系统讲解 Java 面向对象编程的核心知识体系,涵盖类的定义与封装、构造方法与 this/super 关键字、继承与方法重写、多态与向上向下转型、抽象类与接口的区别与设计原则、异常处理机制(try-catch-finally / 自定义异常)、泛型的类型参数与通配符、集合框架(List/Set/Map)的使用与遍历方式,帮助开发者全面掌握 Java 程序设计的核心机制与面向对象思维。

203

2026.04.17

Buffalo框架数据库开发全教程
Buffalo框架数据库开发全教程

本专题围绕Buffalo框架数据库开发,讲解database.yml多环境配置、soda与fizz迁移生成回滚、模型结构体标签、增删改查与条件查询、一对多与多对多关联、数据校验、回调钩子、事务处理及原生SQL执行能力。

80

2026.09.23

热门下载

更多
网站特效
/
网站源码
/
网站素材
/
前端模板

精品课程

更多
热门推荐
/
最新课程
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn