Table of Contents
回复内容:
继承
组合
Home Backend Development PHP Tutorial redis - php两种封装类的优缺点?

redis - php两种封装类的优缺点?

Jun 06, 2016 pm 08:38 PM
oop php redis Exception handling

php很多内置的类或扩展类比较粗糙,需要人为的封装一遍,于是有了两种封装方式,
1直接继承
2内部实例化

如redis类,
可以

<code>namespace lib
class redis extends \Redis {}
</code>
Copy after login
Copy after login

也可以

<code>namespace lib
class redis {
    private $_redis = null;
    public function __construct() {
        $this->_redis = new \Redis()
    }
}
</code>
Copy after login
Copy after login

第一种方法的优点是方便,无须把所有的方法重写一遍,但是不太好统一捕捉异常,
第二种就是麻烦些,需要重写一遍所有的方法,(虽然可以用魔术方法),捕捉异常方便些。
大家用的哪种?为什么呢?

回复内容:

php很多内置的类或扩展类比较粗糙,需要人为的封装一遍,于是有了两种封装方式,
1直接继承
2内部实例化

如redis类,
可以

<code>namespace lib
class redis extends \Redis {}
</code>
Copy after login
Copy after login

也可以

<code>namespace lib
class redis {
    private $_redis = null;
    public function __construct() {
        $this->_redis = new \Redis()
    }
}
</code>
Copy after login
Copy after login

第一种方法的优点是方便,无须把所有的方法重写一遍,但是不太好统一捕捉异常,
第二种就是麻烦些,需要重写一遍所有的方法,(虽然可以用魔术方法),捕捉异常方便些。
大家用的哪种?为什么呢?

继承

继承的特点有

  • ✔实现成本低
  • ✔调用者可以沿用原有的接口使用,学习成本低
  • ✔原有的功能无需任何代码如常工作
  • ✘无法隐藏或改变原有的功能

    • 其实你可以这么做,就好像你确实可以用铁丝去捅插座眼一样
    • 改变输入、改变输出、改变行为都属于改变功能,比如原来抛的异常现在不抛了,原来return false现在变异常了,原来输入的是青椒现在变牛肉了等等
  • ✘正交性弱,没有做到屏蔽父类的依赖,需要更换父类的时候显得脆弱

常见的合适的应用有

  • 增加日志记录等不影响原有逻辑的“旁路逻辑”
  • 增加一些方法,比如原有的某一些方法a()b()c()总是连续一起调用,增加一个doABC()方法

    • 仅限简单的少量的方法,如果要加复杂的功能或者大量的方法,还是建议用组合
  • 增加一些静态/工厂方法,比如new Redis(ip, port) => OurRedis::getInstance()

一句话说就是原有行为不变,is-a的场景用继承。

组合

组合的特点有

  • ✘实现成本略高,创建对象的过程可能会变复杂
  • ✘调用者需要理解新的接口
  • ✘需要转发才能让原有的功能工作
  • ✔很容易隐藏/屏蔽原有的部分功能
  • ✔正交性强,可以通过更换内部的对象适配不同的情况而保持外部接口不变

常见的合适的应用有

  • 一切涉及改变行为的需求
  • 未来依赖会变的场景,比如redis会变成memcache,或者mysql会变mariadb之类
  • 需要屏蔽细节的场景,比如Session Cache等需求确实用到redis,但对外肯定要屏蔽“这是个redis实现的session”。否则恐龙会出现在你背后把你脑袋咬掉

一句话就是某个功能依赖另一个功能,use-ahas-a的场景用组合


偏题,predis用起来还不错,可以一试

如果你看过任何一本设计模式的书,肯定都是推荐你使用第二种。

它们奉行的原则是:组合优于继承

不过,还得看自己需求。如果系统的接口和你的类提供的一致,可以试试第一种。如果不一致,选择第二种。

如果你正在为系统设计 DB 中间层,需要适配不同的数据库,选择第二种。

楼主你干脆用Java吧,别用PHP了。用好一门语言就要掌握这门语言的特性和风格,按照这门语言的风格去行事。

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1660
14
PHP Tutorial
1260
29
C# Tutorial
1233
24
PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP's Purpose: Building Dynamic Websites PHP's Purpose: Building Dynamic Websites Apr 15, 2025 am 12:18 AM

PHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP's Impact: Web Development and Beyond PHP's Impact: Web Development and Beyond Apr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

See all articles