PHP How to pass attribute values between classes

Asked

Viewed 6,962 times

2

I have two distinct User and Comment classes, I use the Comment class to record the comments in the bd, but I need the user attribute that is in the User class that is in the getUsuarioId() method. When I instate the User() object in the Comment class, a new object is created with the zeroed attributes. How could I pass this id value to another class? I tried it with a global variable but it didn’t work.

<?php
	require_once("classes/Conexao.class.php");

	class UsuarioDAO{
		function __construct(){
			$this->con = new Conexao(); 
			$this->pdo = $this->con->Connect(); 
		}

		public function existeUsuario($email){
			
			$query = $this->pdo->prepare("SELECT * FROM 'usuario' WHERE  email = '$email'");
			var_dump($query);
			$query->execute();

			if ($query->rowCount() >= 1){
				return true;
			}else{
				return false;
			}

		}//fecha metodo existe

		public function logar($usuario){
			try{
				$param = array(
					":email" => $usuario->getEmail(),
					":senha" => $usuario->getSenha()
					);
				$query = $this->pdo->prepare("SELECT * FROM usuario WHERE  email = :email AND senha = :senha");
				$query->execute($param); 
				$senha = $usuario->getSenha();

				if ($query->rowCount()>=1) {
					while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
						if ($row['senha'] == $senha) {
							$_SESSION['idUsuario'] = $row['id_usuario'];			
						}
					}
				}
						return $usuario; 
		
			
			} catch(PDOException $ex){ //caso haja erro
				echo "ERRO:"+ $ex->getMessage(); //exibe o erro
			}
		}


		public getIdUsuario(){
			return $_SSESION['idUsuario'];
		}

		public function cadastrar($usuario){
			try {
					$param = array(
					":nome" =>$usuario->getNome(),
					":email" => $usuario->getEmail(),
					":senha" => $usuario->getSenha()
					);

					$email = $usuario->getEmail();

				if ($this->existeUsuario($email)) { 
					echo "Usuário ja cadastrado!";
					return false;
				}else{
					$query = $this->pdo->prepare("INSERT INTO usuario(nome, email, senha) 
                                        VALUES (:nome, :email, :senha)");							
					$query->execute($param);	 			
						return true; 
			
				}
				
			} catch (PDOException $ex) {
				echo "ERRO:"+ $ex->getMessage();	
			}
		}//fecha a funcao

	}//fecha classe
?>
<?php
	class Usuario {
		
		protected $idUsuario;
		protected $nome;
		protected $email;
		protected $senha;
		protected $foto; 


		public function getIdUsuario(){
			return $this->idUsuario;
		}
		public function setIdUsuario($idUsuario){
			$this->idUsuario = $idUsuario;
		}
		public function getNome(){
			return $this->nome;
		}
		public function setNome($nome){
			 $this->nome = $nome;
		}

		public function getEmail(){
			return $this->email;
		}
		public function setEmail($email){
			$this->email = $email;
		}

		public function getSenha(){
			return $this->senha;
		}
		public function setSenha($senha){
			$this->senha = $senha;
		}

		public function getFoto(){
			return $this->foto;
		}
		public function setFoto($foto){
			$this->foto = $foto;
		}


		
		

	}//fecha a classe
?>

<?php

session_start();
require_once("/classes/Conexao.class.php"); //Incluimos o arquivo de conexão.
require_once("classes/entidade/Usuario.class.php");
require_once("classes/dao/UsuarioDAO.class.php");
class comentarioDAO { //Criamos uma classe chamada cometarioDAO

    function __construct() { 
        $this->con = new Conexao(); 
        $this->pdo = $this->con->Connect(); 
    }

    public function cadatrarComentario(comentario $entComentario) { 
        try { 
           
 
            $query1 = $this->pdo->prepare("SELECT id_usuario FROM usuario WHERE email = $email");

            $resultId = $query1->execute(array(':email'=>email));


            while ($row = $resultId->fetch(PDO::FETCH_ASSOC)) {
                        $usuario->setIdUsuario($row['id_usuario']);
                
            }
            $stmt = $this->pdo->prepare("INSERT INTO comentario (comentario, data, hora, id_usuario) 
                                        VALUES ( :comentario, :data, :hora, :idUsuario)");

            $param = array(/
                ":comentario" => $entComentario->getComentario(),
                ":data" => date("Y/m/d"),
                ":hora" => date("h:i:s"),
                ":idUsuario" => $usuario->getIdUsuario()
            );
            
            return $stmt->execute($param); 
        } catch (PDOException $ex) {
            echo "ERRO: " + $ex->getMessage(); 
    }

    //Método de consulta

    public function consultarComentario($pagina) {
        try { //Executa nosso código
            $stmt = $this->pdo->prepare("SELECT * FROM comentarios WHERE cm_pagina = :pagina AND cm_status = 1");
            
            $param = array(":pagina" => $pagina);
            
            $stmt->execute($param); 
            
           return $stmt->fetchall(PDO::FETCH_ASSOC);
            
        } catch (PDOException $ex) { 
            echo "ERRO: " + $ex->getMessage(); 
    }

}

?>

  • 1

    Pass the user_id in the User constructor method, or create an autor_id attribute in the Comment class.

  • That’s the same question your previous question?

  • Yes, @bfavarretto. It is not correct to keep creating threads like this, but I could not solve this problem.

2 answers

2

You can pass the usuario_id for your class ComentarioDAO either by parameter in the constructor (if any), or as a parameter of the function using it:

Examples

class ComentarioDAO {

  /* @var integer
   */
  private $usuario_id;


  /**
   * Instanciate the ComentarioDAO class
   *
   * @param integer $usuario_id User ID.
   */
  function __construct($usuario_id=0) {

    $this->usuario_id = $usuario_id;
  }


  public function fazerQualquerCoisa() {

    echo $this->usuario_id;
  }

  public function fazerQualquerCoisa2($usuario_id=0) {

    echo $usuario_id;
  }
}

Then it would be something inside this kind:

  • Pass as constructor parameter

    $userClass = new usuario();
    
    $commentClass = new ComentarioDAO($userClass->getUsuarioId());
    
    $commentClass->fazerQualquerCoisa();
    
  • Pass as a method parameter:

    $userClass = new usuario();
    
    $commentClass = new ComentarioDAO();
    
    $commentClass->fazerQualquerCoisa2($userClass->getUsuarioId());
    
  • I’m using the classes this way

  • If I create a constructor in the User class how can I get this id in the Comment class?

  • The construct will not allow you to pass value between classes... It can receive values per parameter to make them available for your methods.

0

Search for Orms in php, a very good is the Eloquent, used in Laravel, they already abstract all the DAO and the CRUD

If you don’t want to use Orms, you can place an attribute usuario within the Comentario class, from there just do:

$c = new Comentario;

$c->usuario = $usuario;

If the attributes of the User class are public you can access them normally $c->usuario->id, otherwise use the methods $c->usuario->getId()

Your class Commentary would look like this:

class Comentario {
  public usuario;
  ...  
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.