设计模式 - php中,为什么不在construct中写很多逻辑代码?
今天突然想到了这个问题.
回复内容:
今天突然想到了这个问题.
构造器的目的是init,你在里面完全可以用1W行if else 将所有的逻辑都写在里面,但是你怎么快速定位bug?某个逻辑被修改了,你又得横切你的代码。那么oo的意义何在?
因为构造时一般并不会有复杂逻辑
构造器的目的是init,比如一个必须登录才能看的页面,就可以在构造里判断是否登录了,而不需要在下边的方法里逐个判断,就是说把公用的东西拿到这,可以适当把都需要用到的拿到这里,如果写太多,bug也不好定位
PHP的Class的构造方法算是整个PHP面向过程到面向对象变化中波折最多的一个,甚至连方法名都改动过,所以在很多三方库或是开源程序中,很少有大范围使用构造方法的,目的是为了避免兼容性问题和一些不必要的结果。另外,PHP的构造方法甚至不要求必须执行父类构造,我感觉这看上去会破坏程序流程,特别是接入和修改三方的时候。
每个函数或者方法代码一般不过超过100行,更何况是初始化!!!
代码重构书上普遍都有一个规则好像,
是 function
优于 if ··· else
,
灵活性高
语法 习惯 规范 最佳实践 这是一个人代码风格的来源。
符合语法是最低标准,在构造函数写复杂逻辑是符合语法的。但是不符合规范或者最佳实践。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

To work on file upload we are going to use the form helper. Here, is an example for file upload.

In this chapter, we are going to learn the following topics related to routing ?

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

Validator can be created by adding the following two lines in the controller.

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c
