Html biçimlendirmek için PHP sınıfları kullanarak?

2 Cevap php

Belirli bir site için belirlenmiş bir sınıf var. Bu sitede ben veritabanından veri almak ve bir diziye bu verileri depolamak için farklı işlevlere sahiptir. Ben veri almak ve html içine biçimlendirmek ve veritabanından verileri içeren html döndürür aynı sınıf içinde diğer işlevlere sahiptir.

Örneğin ...

function GetUserProfile($userID){

  $query = 'SELECT * FROM users WHERE userID='.$userID; 

  .......

  blah blah blah 

  .......

  $user = mysqli->fetch_assoc(); 

  return $user;

}

function FormatUserProfile($user, $showDesc = false){ 

  $profile = '< h1 >'.$user['userName'].'< / h1 >'; 

  if($showDesc){ 

    $profile .= '< div >'.$user['description'].'< / div >'; 

  } 

  return $profile; 

}

...

So if i had a function to solely gather information, and another function to solely format that gathered information. Mainly because I will be showing the same data on different pages, but Different pages show different data, like a search would only bring up the users name, where as the users profile page would bring up the username and the description for example.

Bu iyi bir uygulama mı, yoksa bunu yapmak için daha iyi bir yolu var mı?

2 Cevap

Bu iyi bir uygulamadır. Şahsen ben şu şablonu "motor" kullanın:

<?php
class Template{
    static function show($path, $arg = NULL){
        include "templates/$path.php";
    }

    static function get($path, $arg = NULL){
        ob_start();
        self::show($path, $info);
        $block = ob_get_contents();
        ob_end_clean();
        return $block;
    }
}

Senin durumunda şablon bu gibi olurdu:

<?php
echo '<h1>'.$arg['user']['userName'].'</h1>'; 
if($arg['showDesc']){
  echo '<div>'.$arg['user']['description'].'</div>'; 
}
?>

Sen şablon argümanları ile dizi açmak olabilir, ama ben bir yerde tüm tutmak için tercih, bu yüzden kod daha az kafa karıştırıcı. (Her zaman girişten geliyor biliyorum, ve ne şablonda bu şekilde tanımlanır. Kısa şeyleri tutmak için, $ çok arg yerine _ $ kullanabilirsiniz.) Bu gibi küçük Örneğin, fayda, belirgin değildir PHP'nin kendi çiftleşmiş yeteneklerini kullanmak gibi ancak daha büyük şablonları için, değişken manipülasyon bir çok kaydedebilirsiniz.

You can use Smarty template engine or something similar.

It şablonları ayrı depolanır ve bu gibi bakmak: http://www.smarty.net/sampleapp/sampleapp%5Fp5.php