Obviously, anything that needs to interact with the database will extend this class.
从OOP的角度来看,这没有任何意义.当某个类扩展另一个暗示“是一个”关系的类时.如果你走这条路线,你将很难不违反OCP这是SOLID中的一个字母.
I’ve been flipping back and forth on how to make sure that there is only ever one connection, or PDO object, in a script because some pages will need more than one class that extends Connector.
简单!只需创建一个实例.
Many people seem to recommend a Singleton pattern for this purpose, but the way I currently do it seems to accomplish the same thing.
很多人都不喜欢OOP原则.使用单身人士只是引入了一个“花哨的”global instance / state.
Does this code actually make sense and or am I misunderstanding static properties somehow?
说实话,这更多是对OOP的误解.
Is it bad design/practice and or does Singleton have more advantages?
往上看.
你应该做什么(在OOP中)是inject the database connection进入需要它的类.这使您的代码松散耦合,从而使您的代码更易于维护,可测试,可调试和灵活.
另外,我真的不明白为什么你需要为pdo连接创建一个数据库类,因为PDO API本身已经是OOP.因此,除非你有一个真正的理由为PDO编写一个适配器(可能是这种情况,因为有一些),我会放弃它.
我的€0.02
–
为了回应您的编辑:
The Connector class wasn’t meant to exist just to hold the PDO object. It’s destructor closes the connection(makes it null).
通常根本不需要关闭连接.处理请求后,连接将自动关闭(除非我们讨论的是持久连接).
and it contains functions such isValueTaken, which checks if a value is already in the database. It has the following abstract functions
这听起来像是另一堂课的工作.
For example I have a User class that extends Connector. It’s defines setData() to register a user in the database. I don’t know if this makes a difference to the response.
不,我的观点仍然存在.用户无需从数据库继承.这听起来不奇怪.从数据库继承的用户(我不想见到那个人).如果需要,您应该将数据库连接注入用户.