Jump to content
Vinicius Cainelli

Compartilhar variáveis entre dois métodos

Recommended Posts

Basicamente, o que eu tenho em uma classe são dois métodos.

- getEstablishment($establishmentId) que pega todos os dados de um determinado estabelecimento baseado no id passado.
- getAllEstablishments() que me da um array com todos os dados de todos os estabelecimentos que tenho no meu banco

Se repararem no código, vão ver que repete muitas variaveis, existe alguma forma de eu compartilha-lhas entre esses métodos?

 


  function getEstablishment($establishmentId)
  {
    $query = "SELECT *
      FROM establishment
      WHERE establishment_id='{$establishmentId}'
      LIMIT 0,1";
    $result = mysqli_query($this->connection, $query);
    $establishmentArray = mysqli_fetch_assoc($result);

    $docNumber = $establishmentArray['doc_number'];
    $legalName = $establishmentArray['legal_name'];
    $socialName = $establishmentArray['social_name'];
    $type = $establishmentArray['type_id'];
    $email = $establishmentArray['email'];
    $website = $establishmentArray['website'];
    $plan = $establishmentArray['plan_id'];
    $agreeTerm = $establishmentArray['agree_term'];
    $address = $establishmentArray['address'];
    $district = $establishmentArray['district'];
    $city = $establishmentArray['city_id'];
    $zipCode = $establishmentArray['postal_code'];
    $phone = $establishmentArray['phone'];
    $created = $establishmentArray['created'];
    $lastUpdate = $establishmentArray['last_update'];

    $establishment = new Establishment($docNumber, $legalName, $socialName, $type, $email, $website, $plan, $agreeTerm, $address, $district, $city, $zipCode, $phone, $created, $lastUpdate);

    return $establishment;
  }

  function getAllEstablishments()
  {
    $establishments = array();
    $query = "SELECT *
      FROM establishment
      ORDER BY establishment_id DESC";

    $result = mysqli_query($this->connection, $query);

    while ($establishmentArray = mysqli_fetch_assoc($result)) {

      $establishmentId = $establishmentArray['establishment_id'];
      $docNumber = $establishmentArray['doc_number'];
      $legalName = $establishmentArray['legal_name'];
      $socialName = $establishmentArray['social_name'];
      $type = $establishmentArray['type_id'];
      $email = $establishmentArray['email'];
      $website = $establishmentArray['website'];
      $plan = $establishmentArray['plan_id'];
      $agreeTerm = $establishmentArray['agree_term'];
      $address = $establishmentArray['address'];
      $district = $establishmentArray['district'];
      $city = $establishmentArray['city_id'];
      $zipCode = $establishmentArray['postal_code'];
      $phone = $establishmentArray['phone'];
      $created = $establishmentArray['created'];
      $lastUpdate = $establishmentArray['last_update'];

      $establishment = new Establishment($docNumber, $legalName, $socialName, $type, $email, $website, $plan, $agreeTerm, $address, $district, $city, $zipCode, $phone, $created, $lastUpdate);
      $establishment->setId($establishmentId);

      array_push($establishments, $establishment);
    }
    return $establishments;
  }

 

Share this post


Link to post
Share on other sites

Em vez de variável usa propriedade...

  • +1 1

Share this post


Link to post
Share on other sites

Se um trecho de código se repete, isole-o em um método:

function getEstablishment($establishmentId)
{
    $query = "SELECT *
    FROM establishment
    WHERE establishment_id='{$establishmentId}'
    LIMIT 0,1";
    $result = mysqli_query($this->connection, $query);        
    return $this->createObject(mysqli_fetch_assoc($result));
}

function getAllEstablishments()
{
    $establishments = array();
    $query = "SELECT *
    FROM establishment
    ORDER BY establishment_id DESC";

    $result = mysqli_query($this->connection, $query);

    while ($establishmentArray = mysqli_fetch_assoc($result)) {
        $establishments[] = $this->createObject($establishmentArray);
    }
    
    return $establishments;
}

private function createObject(array $rawEstablishment)
{
    $docNumber = $rawEstablishment['doc_number'];
    $legalName = $rawEstablishment['legal_name'];
    $socialName = $rawEstablishment['social_name'];
    $type = $rawEstablishment['type_id'];
    $email = $rawEstablishment['email'];
    $website = $rawEstablishment['website'];
    $plan = $rawEstablishment['plan_id'];
    $agreeTerm = $rawEstablishment['agree_term'];
    $address = $rawEstablishment['address'];
    $district = $rawEstablishment['district'];
    $city = $rawEstablishment['city_id'];
    $zipCode = $rawEstablishment['postal_code'];
    $phone = $rawEstablishment['phone'];
    $created = $rawEstablishment['created'];
    $lastUpdate = $rawEstablishment['last_update'];

    $establishment = new Establishment($docNumber, $legalName, $socialName, $type, $email, $website, $plan, $agreeTerm, $address, $district, $city, $zipCode, $phone, $created, $lastUpdate);
    $establishment->setId($rawEstablishment['establishment_id']);

    return $establishment;
}

 

Outra coisa que pode realizar é criar um método instrospect. Ou seja, deixar a responsabilidade para o próprio objeto Establishment:

class Establishment
{
    public function instrospect(array $raw)
    {
        $this->id = $raw['establishment_id']);
        $this->docNumber = $raw['doc_number'];
        $this->legalName = $raw['legal_name'];
        
        /** e demais inclusões **/
    }
}

Seus métodos, assim, serão simplificados:

function getEstablishment($establishmentId)
{
    $query = "SELECT *
    FROM establishment
    WHERE establishment_id='{$establishmentId}'
    LIMIT 0,1";

    $result = mysqli_query($this->connection, $query);

	$establishment = new Establishment();
    $establishment->instrospect(mysqli_fetch_assoc($result));

    return $establishment;
}

function getAllEstablishments()
{
    $establishments = array();
    $query = "SELECT *
    FROM establishment
    ORDER BY establishment_id DESC";

    $result = mysqli_query($this->connection, $query);

    while ($establishmentArray = mysqli_fetch_assoc($result)) {
        $establishment = new Establishment();
        $establishment->instrospect($establishmentArray);

        $establishments[] = $establishment;
    }
    
    return $establishments;
}

 

A propósito, sobre array_push:

Note: If you use array_push() to add one element to the array it's better to use $array[] = because in that way there is no overhead of calling a function.

Logo, substituí o seu array_push por:

$establishments[] = $this->createObject($establishmentArray);

 

  • +1 1

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By rjlfurtado
      Segue abaixo o exemplo de como seria feito em SQL:
      CREATE TABLE tabela ( campo1 DOUBLE, campo2 DOUBLE, divisao DOUBLE AS (campo1/campo2) ); Agora eu preciso criar uma migração no Laravel 6, segue exemplo abaixo:
      $table->integer('qtd_saida'); $table->decimal('valor_uni', 8, 2); $table->double('valor_total')->as(qtd_saida * valor_uni);  
    • By Marxrj
      Olá a todos!,
      Queria aqui uma dica se alguém sabe como alinhar fotos no centro pelo bootstrap.
      Usando o padrão fotos retratos fica como abaixo
      __________  __________
      __________
       
      Mas eu queria que quando tivesse um número impar, a foto não ficasse alinhada na esquerda e sim centralizada como abaixo
      __________  __________
                __________
       
      Estou usando este padrão abaixo aonde ele alinha duas fotos ao lado, mas quando tem somente um ou em número impar, essa não centraliza e sim fica a esquerda.
      <div class="col-xs-12 col-sm-10 col-lg-6 col-md-3">
    • By JoãoRicardo.Lima
      Olá pessoal blz?.
      Estou com problemas para ler um xml, estou pegando ele com simplexml_load_file(), quando eu dou um vardump ele me mostra todas as propriedades e tals, mas quando eu tento pegar a propriedade(exemplo $xml->emit) ele me retorna null, abaixo está o código.
       
      $arquivo = $_FILES['xml_conta']; $xml = simplexml_load_file($arquivo['tmp_name']); var_dump($xml->ide); Já tentei pegar o arquivo direto do diretório mas da no mesmo. Abaixo o meu var_dump().
       
      object(SimpleXMLElement)#2 (3) { ["@attributes"]=> array(1) { ["versao"]=> string(4) "4.00" } ["NFe"]=> object(SimpleXMLElement)#4 (2) { ["infNFe"]=> object(SimpleXMLElement)#6 (9) { ["@attributes"]=> array(2) { ["versao"]=> string(4) "4.00" ["Id"]=> string(47) "NFe51191203927792000132550010003900572477841258" } ["ide"]=> object(SimpleXMLElement)#8 (22) { ["cUF"]=> string(2) "51" ["cNF"]=> string(8) "47825479" ["natOp"]=> string(33) "Venda Terceiros" ["mod"]=> string(2) "50" ["serie"]=> string(1) "1" ["nNF"]=> string(6) "397894" ["dhEmi"]=> string(25) "2019-12-05T18:35:33-04:00" ["dhSaiEnt"]=> string(25) "2019-12-05T18:35:33-04:00" ["tpNF"]=> string(1) "1" ["idDest"]=> string(1) "1" ["cMunFG"]=> string(7) "51074" ["tpImp"]=> string(1) "3" ["tpEmis"]=> string(1) "2" ["cDV"]=> string(1) "5" ["tpAmb"]=> string(1) "2" ["finNFe"]=> string(1) "2" ["indFinal"]=> string(1) "1" ["indPres"]=> string(1) "1" ["procEmi"]=> string(1) "0" ["verProc"]=> string(7) "3.5.1.2" ["dhCont"]=> string(25) "2019-12-05T15:32:22-04:00" ["xJust"]=> string(23) "sem conexao com o sefaz" }  
    • By granderodeo
      Queria que quando o usuário efetuasse o login, exibisse a mensagem "Login efetuado com sucesso", e se houve algum erro também exibisse uma mensagem de erro.
       
      valida_login.php
      <?php session_start(); include_once("config/conexao_fornec.php"); if (isset($_POST['enviar'])) { if (!empty($_POST['login']) || !empty($_POST['senha'])) { $login=$_POST['login']; $senha=MD5($_POST['senha']); $comando="SELECT * FROM usuarios, orders WHERE email = '$login' and senha= '$senha' and id_usuario"; $enviar=mysqli_query($conn, $comando); $resultado= mysqli_fetch_assoc($enviar); if ($resultado) { $_SESSION['id_usuario']=$resultado['?']; $_SESSION['order_date']=$resultado['order_date']; $_SESSION['order_id']=$resultado['order_id']; $_SESSION['login']=$resultado['login']; $_SESSION['senha']=$resultado['senha']; $_SESSION['email']=$resultado['email']; $_SESSION['nome']=$resultado['nome']; $_SESSION['id']=$resultado['id']; $_SESSION['seguranca']=$resultado['seguranca']; header("location:../index.php"); exit; }else{ $_SESSION['msg'] = "<div class='alert alert-success'>Versão e Revisão cadastrada com sucesso!</div>"; } }else{ $_SESSION['mensagem']="<div class='alert alert-danger alert-dismissible text-center' style='width: 24.5%; position: absolute; margin-left: 38.2vw; margin-top: 3vh;'><button type='button' class='close' data-dismiss='alert'>&times;</button>Ops! Alguns dos campos ficou em branco.</div>"; header("location:https://compre-aqui.com/users/"); exit; } }else{ header("location:users"); exit; } ?>  
       
      Corpo do login
      <section class="hero is-success is-fullheight"> <div class="hero-body"> <div class="container has-text-centered"> <div class="column is-4 is-offset-4"> <h2 class="text-center mb-4">Faça seu login</h2> <div class="box"> <form action="validar_login.php" method="POST"> <div class="field"> <div class="form-group"> <label for="name">E-mail</label> <input name="login" id="name" type="name" class="form-control" placeholder="Nome completo"> </div> </div> <div class="field"> <div class="form-group"> <label for="senha">Senha</label> <input name="senha" id="senha" class="form-control" type="password" placeholder="Senha"> </div> </div> <button type="submit" class="btn btn-info btn-block" name="enviar">Realizar login</button> </form> <hr style="background-color: white;"> <a href="https://compre-aqui.com/users/cadastro.php" class="btn btn-info btn-block mt-2">Esqueci minha senha</a> <a href="https://compre-aqui.com/users/cadastro.php" class="btn btn-info btn-block mt-2">Cadastre-se</a> </div> </div> </div> </div> </section>  
    • By ndias
      Estou com duvida se minha conexão está encerrando.
       
      Utilizo PDO para me conectar:
       
      public static function getDb(){ try { $db = new \PDO( 'mysql:host=localhost;dbname=xyz;charset=utf8', 'xyz', 'xyz1234', array( \PDO::ATTR_ERRMODE => \PDO::ERRMODE_EXCEPTION ) ); return $db; } catch (PDOException $e) { echo "Erro de Conexão " . $e->getMessage() . "\n"; exit; } } public function __construct(\PDO $db) { $this->db = $db; } public function verifica(){ $sql = "SELECT * FROM tabela "; $result = $this->db->query($sql); $rows = $result->fetch(); if($rows){ }else{ } } public function __destruct() { unset($this->db); foreach ($this as $key => $value) { unset($this->$key); } } Estou fazendo certo? Como posso verificar se a conexão está ficando aberta?
×

Important Information

Ao usar o fórum, você concorda com nossos Terms of Use.