2010-11-11 78 views
0

我在php中寫了一個類,我需要在類的函數中寫入的所有引用都有一個前綴。這是...PHP OOP鏈接製造商?

class MyClass 
{ 
    function echoing() 
    { 
     $class = new LinkMaker(); 
     return $class->create(array('href' => 'popular/books/', 'title' => 'Popular books of 2010')); 
    } 
} 

然後在類LinkMaker中,我添加了一個前綴鏈接..是否所有正確的我想要做的? 抱歉,英語不好

回答

1

我想我明白你在說什麼。你想在服務器端構建DOM。

下面是我寫的一個重載的PHP 5類,它是這樣做的。它將採用任何HTML 5錨定屬性。

用法:

<? 
    $links = array(
     new BabyLink(array('href' => '/home', 'name' => 'home', 'title' => 'Home Page', 'label' => 'Home')), 
     new BabyLink(array('href' => '/about', 'name' => 'account', 'title' => 'About This Site', 'label' => 'About')), 
     new BabyLink(array('href' => '/contact', 'name' => 'contact', 'title' => 'How To Contact Us', 'label' => 'Contact')), 
     new BabyLink(array('href' => '/logout', 'name' => 'logout', 'title' => 'Log Out', 'label' => 'Logout')) 
     ); 

foreach ($links as $link) 
    { 
    $link->render(); 
    } 

<? 

/** 
* BabyLink HTML5 Anchor Link Model 
* @author Warren Stevens ([email protected]) 
* @package Baby 
**/ 

class BabyLink 
    { 

    public $id = false; 

    protected $me = array(); 

    public $fields = array('id', 'accesskey', 'class','contenteditable', 'contextmenu', 'data-', 'draggable', 'hidden', 'href', 'hreflang', 'item', 'itemprop', 'label', 'lang', 'media', 'ping', 'rel', 'spellcheck', 'style', 'subject', 'tabindex', 'target', 'title', 'type'); 

    function __construct(array $a) { $this->set($a); } 

    /** 
    * @param string 
    * @param array 
    **/ 
    function __call($k, $args = array()) { return $this->me[$k]; } 

    function get() { return $this->me; } 

    function set(array $a) 
     { 
     foreach($this->fields as $k) { if(isset($a[$k])) { $this->me[$k] = $a[$k];}} 
     $this->id = $this->me['id']; 
     } 

##### PUBLIC 


    public function render() 
     { 
     $str = '<a '; 
     foreach ($this->me as $k => $v) 
      { 
      $str .= $k.'="'.$v.'" '; 
      } 
     $str .= '>'.$this->label().'</a>'; 
     print $str; 
     } 
    }