简体   繁体   English

PHP OOP-Php对象扩展了Mysql Object =多个Mysql连接?

[英]PHP OOP - Php objects extends Mysql Object = Multiple Mysql Connection?

I'm currently working on a Shopping Cart in which I use a custom Mysql Class to send query to the db. 我目前在使用自定义Mysql类将查询发送到数据库的购物车上工作。

On this project, I plan to extends this Mysql Class for each Object that I will use : Category, Product, Shopping Cart. 在该项目上,我计划为我将使用的每个对象扩展此Mysql类:类别,产品,购物车。

If I create a class like this one: 如果我创建一个像这样的类:

class Catalog_Categories extends Mysql{}

And then another one like this: 然后再这样一个:

class Catalog_Products extends Mysql{}

Are those classes using the same Mysql Object to connect on DB or are they using 2 separate connections? 这些类是使用相同的Mysql对象在数据库上进行连接还是使用2个单独的连接?

I'm a little bit lost. 我有点迷路了。

Thanks! 谢谢!

Carl. 卡尔

That depends on how your Mysql class is written. 这取决于您的Mysql类的编写方式。 If you write it using a Singleton pattern, it will maintain one database instance. 如果使用Singleton模式编写它,它将维护一个数据库实例。 You could write it as a Factory pattern and have it generate a new instance for each object that uses it. 您可以将其编写为Factory模式,并为使用它的每个对象生成一个新实例。 There are many other patterns and possibilities available so it all just depends on how you want it to work and how you wrote the custom Mysql class. 还有许多其他模式和可能性可用,因此所有这些都取决于您希望它如何工作以及如何编写自定义Mysql类。

Assuming that you are creating a database connection in your Mysql class, every object your create of any of the extending classes, will create a new DB connection. 假设您正在Mysql类中创建数据库连接,则任何扩展类创建的每个对象都将创建一个新的DB连接。

There are several ways to avoid this, for example, you can create one global connection to your database and pass that connection to the constructor of your class so that they all will use that same connection. 有几种方法可以避免这种情况,例如,您可以创建一个到数据库的全局连接,并将该连接传递给类的构造函数,以便它们都将使用同一连接。

Are those classes using the same Mysql Object to connect on DB or are they using 2 separate connections? 这些类是使用相同的Mysql对象在数据库上进行连接还是使用2个单独的连接?

We cannot answer this question until we see the complete code. 在看到完整的代码之前,我们无法回答此问题。

But extending in this case looks like a bad idea. 但是在这种情况下扩展似乎是个坏主意。 If you cannot say that class A is a class B - then you should prefer composition over inheritance. 如果您不能说class A is a class B -那么您应该更喜欢组合而不是继承。 This means that Catalog_Products should have a reference to mysql object, but shouldn't extend it. 这意味着Catalog_Products应该具有对mysql对象的引用,但不应扩展它。

To get you idea when inheritance is justified is class mysql extends database . 为了让您有一个合理的理由继承继承是class mysql extends database In this case you can say "mysql is a database", so extension here looks reasonable as long as database class encapsulates the common logic, and mysql class represents more detailed specifics. 在这种情况下,您可以说“ mysql是数据库”,因此,只要database类封装了通用逻辑,并且mysql类代表更详细的细节,此处的扩展看起来就很合理。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM