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 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?
    • By granderodeo
      <!-------------------------------- PEDIDOS -------------------------> <div class="table-responsive mt-2"> <table class="table table-bordered table-striped text-center"> <thead> <tr> <td colspan="8"> <h4 class="text-center text-info m-0">Pedidos realizados</h4> </td> </tr> <tr> <th>ID pedido</th> <th>Nome cliente</th> <th>E-mail</th> <th>Endereço</th> <th>Número da casa</th> <th>Referência</th> <th>ID cliente</th> </tr> </thead> <tbody> <?php require 'conexao_pedidos.php'; $stmt = $conn->prepare("SELECT * FROM orders"); $stmt->execute(); $result = $stmt->get_result(); $grand_total = 0; while($row = $result->fetch_assoc()): ?> <tr> <td> <?= $row['order_id'] ?></td> <td> <?= $row['order_name'] ?></td> </td> <td><?= $row['order_email'] ?> </td> <td> <?= $row['order_endereco'] ?> </td> <td> <?= $row['order_numero'] ?> </td> <td><?= $row['order_referencia'] ?></td> <td><?= $row['id_usuario'] ?> </td> <td> <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal<?= $row['order_id'] ?>"> <i class="fa fa-info-circle"></i> Produtos </button> </td> </tr> <?php endwhile; ?> </tbody> </table> </div> <?php require 'conexao_pedidos.php'; $stmt = $conn->prepare("SELECT * FROM orders"); $stmt->execute(); $result = $stmt->get_result(); $grand_total = 0; while($row = $result->fetch_assoc()): ?> <div class="modal fade" id="exampleModal<?= $row['order_id'] ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Modal title</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">×</span> </button> </div> <div class="modal-body"> <?= $row['order_id'] ?> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> <?php endwhile; ?>  
    • By granderodeo
      Tenho as tabelas 'orders' e 'orders_items'. Quando o cliente faz o pedido no site, com nome, endereço, telefone etc, os dados vão para a tabela orders, já os produtos que o cliente pediu vão para a tabela 'orders_items'. A forma que achei de saber qual pedido é de qual cliente, foi dando um id para cada pedido, e inserindo esse mesmo id em ambas tabelas. Agora estou há fazer um painel administrativo para ter uma melhor visibilidade dos pedidos. O que eu fiz no painel, foi exibir todos os pedidos com as informações, e ao lado de cada pedido um botão que exibirá os produtos pedidos por aquele usuário, inclusive vou deixar imagem de como está. Só que quando eu clicar em produtos, mostre somente os produtos comprados por aquele usuário, que como eu disse anteriormente está 'controlado por ID pedido'. Então quero pegar os dados da tabela 'orders_items' relacionados ao tal cliente, me perdoem se não expliquei direito, mas acredito que dê para entender. 
       
      <body> <!-------------------------------- PEDIDOS -------------------------> <div class="table-responsive mt-2"> <table class="table table-bordered table-striped text-center"> <thead> <tr> <td colspan="8"> <h4 class="text-center text-info m-0">Pedidos realizados</h4> </td> </tr> <tr> <th>ID pedido</th> <th>Nome cliente</th> <th>E-mail</th> <th>Endereço</th> <th>Número da casa</th> <th>Referência</th> <th>ID cliente</th> <!------ REMOVER TODOS ITENS DO CARRINHO -----> <!------ FIM REMOVER TODOS ITENS DO CARRINHO -----> </tr> </thead> <tbody> <?php require 'conexao_pedidos.php'; $stmt = $conn->prepare("SELECT * FROM orders"); $stmt->execute(); $result = $stmt->get_result(); $grand_total = 0; while($row = $result->fetch_assoc()): ?> <tr> <td> <?= $row['order_id'] ?></td> <!-- ID do produto do BD para o carrinho --> <td> <?= $row['order_name'] ?></td> </td> <td><?= $row['order_email'] ?> </td> <td> <?= $row['order_endereco'] ?> </td> <td> <?= $row['order_numero'] ?> </td> <!---- Aumentar ou Diminuir a quantidade do produto -----> <td><?= $row['order_referencia'] ?></td> <!---- Aumentar ou Diminuir a quantidade do produto -----> <!---- Fim Aumentar ou Diminuir a quantidade do produto -----> <td><?= $row['id_usuario'] ?> </td> <!-- preço total do carrinho --> <!------- REMOVER ITEM DO CARRINHO ------> <td> <button type="button" class="btn btn-danger" data-toggle="modal" data-target="#exampleModal"> <i class="fa fa-info-circle"></i> Produtos </button> </td> <!------- FIM ITEM REMOVER DO CARRINHO -------> </tr> <?php endwhile; ?> </tbody> </table> </div>  

    • By manolegal
      Boa tarde
      Gostaria de colocar o valor de um campo bootstrap/vue.js em uma variável php, porém não estou conseguindo. É a primeira vez que estou trabalhando com vue.
      O campo está trazendo o valor correto:
      <section class="scans"> <h2>Scans</h2> <ul v-if="scans.length === 0"> <li class="empty">No scans yet</li> </ul> <transition-group name="scans" tag="ul"> <li v-for="scan in scans" key="scan.date" title="scan.content">{{ scan.content }}</li> </transition-group> </section> var app = new Vue({ el: '#app', data: { scanner: null, activeCameraId: null, cameras: [], scans: [] }, mounted: function () { var self = this; self.scanner = new Instascan.Scanner({ video: document.getElementById('preview'), scanPeriod: 5 }); self.scanner.addListener('scan', function (content, image) { var element = document.getElementById('valor'); element.innerHTML = content self.scans.unshift({ date: +(Date.now()), content: content }); }); Instascan.Camera.getCameras().then(function (cameras) { self.cameras = cameras; if (cameras.length > 0) { self.activeCameraId = cameras[1].id; self.scanner.start(cameras[1]); } else { console.error('Nenhuma Câmera conectada. Verifique!'); } }).catch(function (e) { console.error(e); }); }, methods: { formatName: function (name) { return name || '(unknown)'; }, selectCamera: function (camera) { this.activeCameraId = camera.id; this.scanner.start(camera); } } }); Preciso pegar o valor escaneado constante no campo, para passar para próximo formulário. No aguardo.
    • By Porta
      Moderador... Pode apagar este topico?
       
       
×

Important Information

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