PHP How to pass attribute values between classes

2

I have two distinct User and Comment classes, I use the CommentState class to write comments to bd, but I need the user_id attribute that is in the User class that gets in the getUsuarioId () method. When I instantiate the User object () in the Comment class, a new object with the attributes is zeroed. How could I pass this id value to another class? I tried with a global variable but it did not 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(); 
    }

}

?>
    
asked by anonymous 31.03.2015 / 17:12

2 answers

2

You can pass usuario_id to your class ComentarioDAO either by parameter in the constructor (if it exists) or as a parameter of the function that uses 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 like this:

  • 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());
    
31.03.2015 / 17:25
0

Look for ORMs in php, a very good one is Eloquent, used in Laravel, they already abstract all DAO and CRUD

If you do not want to use ORMs, you can put a usuario attribute within the Comment class, so 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 $c->usuario->getId()

Your Comment class would look like this:

class Comentario {
  public usuario;
  ...  
}
    
31.03.2015 / 18:20