I have two classes (user and ad) and I want to get independent data (That is, they do not have FK in common) from the two tables with the same names as the classes. From the two tables I have a PDO initialize function. The question is, can't I send two connections at the same time? That is, if I create a user object and another ad and, for example, I want to display the data from both tables on the screen, is it normal for me to get an error?
<?php
$usuario = new Usuario;
$anuncio = new Anuncio;
$usuario->obtener_datos();
$anuncio->obtener_datos();
?>
Thanks greetings
It is normal that you get an error, because it is the Conexion.php file, you have declared it twice using the reserved word
require('Conexion.php')
in the User.php and Advertisement.php classes.I recommend you place the reserved word inside both classes
require_once('Conexion.php')
instead ofrequire('Conexion.php')
because you don't know if in the future you will occupy the Announcement class first or other classes. PHP will check if the file has already been requested and if so, it is not required again.Source: require_once PHP
You should not require the connection within the class
Usuario
, or within the classAnuncio
, or within any class.A class has to be thought of as a mold that serves to make objects of that type, regardless of the context from which it is made.
The database is only one possible context or scenario among many. Let's imagine that the context diversifies in the future, and the data of
Usuario
or any other class is obtained not only from the database, but also from an API in the form of JSON, or from a WebService in the form of XML... When you want to pull the classUsuario
you will always have to drag with the connection, even in those contexts where you don't need it.When classes are designed, you have to ask yourself what is proper, what is intrinsic, what makes that class be (from a metaphysical point of view) . That's the only thing that should be in the class
Usuario
. Everything else must be created outside, in the context where it will be used.Simple example of a class
User
:As you can see, no connection is created inside the class. The connection must be created outside, in the context. Also, when you put the connection inside, you give up a big advantage that PDO has, which is mapping a result to a class 1 .
Let's see an example of contextual use:
Context 1: Database
Context 2: An API that returns JSON
Here
$mJson
it would be a JSON with the same properties of your classUser
and you could use your own or third-party mapper to$mJson
create an instance of the classUser
. Thus, we can imagine any other context, such as a WebService, or a Firebase object or others. In any case, you could use itUser
as a true mold to make objects of the class from any contextUser
.