开发者

PHP OOP QUESTION

I'm new to PHP OOP. The project need a site class and the below is my code ():

class Sites {
    private $siteName;
    private $location;
    private $postcode;


    function  __constr开发者_开发知识库uct($name, $loc, $pc) {
        $this->siteName = $name;
        $this->location= $loc;
        $this->postcode = $pc;

        //use "insert SQL" to store new added site info to DB
        $insertSQL = "INSERT INTO table_name (siteName, location, postcode) VALUES ($siteName, $location, $postcode)";

    }

    function getSiteName($SiteID){

        selectSiteName = "SELECT siteName FROM site WHERE siteID = $SiteID";

        return $this->siteName;
    }

    function getSiteLocation($SiteID){

        selectLocation = "SELECT location FROM site WHERE siteID = $SiteID";

        return $this->location;
    }

    function getPostCode($SiteID){

        selectPostcode = "SELECT postcode FROM site WHERE siteID = $SiteID";

        return $this->postcode;
    }

    function getSiteID(){

        //what shoud write here?
        return $this->siteID;
    }
}

Fields in the Site Table include 'siteName', 'location', 'postcode' and 'siteID'. Here 'siteID' is Primary key and AUTO INCREMENT value.

I have few questions:

  1. is the above code correct?

  2. How to get 'SiteID'? For example, sitename is 'ABC', Should get ID by using "SELECT * FROM site WHERE siteName = 'ABC'". But site name is not unique value.

  3. For methods like 'DeleteSiteByID', 'EditSiteByID', 'hasSubSites',shold those methods be in the Site Class?

Thanks for all your help.


The constructor is wrong. It should be

function  __construct($siteName, $location, $postcode) {
    $this->siteName= $siteName;
    $this->location= $location;
    $this->postcode= $postcode;
}

Because they are the properties you declared in your class.

I suggest you declare another property: public $id

Are you storing the Site into the database as soon as it is instantiated? Or do you have a save() method?

If you are storing it as soon as it is instantiated, then mysql_insert_id() will be able to give you the Site's ID.

But if not, then query using both site name and location. I think it combination will be unique enough.

If you do declare the id property, then the parameters of the methods are not necessary. You simply use $this->id.

For the last question, it depends on you. But I would prefer that they be also class methods.


  1. The PHP interpreter will tell you :)
  2. This is not about your object, but about your database structure. If your site name is not unique, you should pass an id when constructing the object.
  3. They could.

Your object seems to resemble an Active Record Pattern. Have a look at this: http://en.wikipedia.org/wiki/Active_record_pattern


1- You should add a visibility to your method like :

public function __construct(){}

You should assign the constructor parameters to the previously declared members like :

public function __ construct($siteName, $location, $postcode){
    $this->siteName= $siteName;
    $this->location= $location;
    $this->postcode= $postcode;
}

2- Im'not sure to understand what you mean here , but the id should be a member of your class which is filled when a new object is created.

3- I don't think so , this kind of method should be in some DB adapter which , for example, could return a Sites object for a specific query on the DB.


  1. Mostly (see ROlandos answer) – but there isn't much to do wrong on class-stub without content.
  2. Usually I select such objects via the ID, but you can always check multiple columns, e.g. the name and location must match to return the correct ID.
  3. They should. Where else do want to store them instead?

You also can't use int for type hinting: "Type Hints can only be of the object and array (since PHP 5.1) type. Traditional type hinting with int and string isn't supported."


Let me answer your questions popint-wise.

  1. Your code is not correct.The parameters you are passing to the functions are not recognized by php. you should instead try

    function getSiteName($SiteId){
         //statements
        }
    
  2. Your second question is a bit confusing. It seems more like a database related problem.To get the ID field the best way is to return it via an object.Instead of trying to find the ID from other fields you should try and get other fields from the ID.(Considered as a good practice)

  3. Yes the methods you prescribed should stay in the site class,as they deal with the data in the sites table.

Can help you better if you can improve your questions and explain your problems in details.


a) I guess the constructor method should be like this, coz you declared the class properties with other names...

function  __construct($siteName, $location, $postcode) {
    $this->siteName = $siteName;
    $this->location = $location;
    $this->postcode = $postcode;
}

b) you should include in the class an id, so you can construct it with the id also and later retrieve the id if needed. for example:

$site_parameters = DB::query("SELECT id, sitename, location, postcode FROM sites WHERE sitename='foo' LIMIT 1");

extract($site_parameters);

$foo_site = new Site($sitename, $location, $postcode, $id);

if you implement the method Site::getId(); you could retrieve the id for any other method that would require the id, for example a class called links:

$site_links = $links->getSiteLinksBySiteId($foo_site->getId());

c) I won't include deleteSiteById etcetera in that class, I would include them in a class that handles the the sites, usually the model that works against the database.


1- In my opinion that's better to use PHP magic methods and build your class in this way :

<?php
class Sites {
    private $siteName = "";
    private $Location = "";
    private $postCode = "";
    private $siteID   = "";
    private $allSites;//if you want to return all sites info you should set this property 

    public function __construct()
    {
        $this->allSites = array();
    }

    public function __set($field,$value)
    {
        switch($field){
             case "siteName":
                  $this->siteName= $value;//do not forget validation before set
                 break;
             case "siteID":
                  $this->siteID= $value;//do not forget validation before set
                 break;
             case "Location":
                 $this->Location = $value;//do not forget validation before set
                 break;
             case "postCode":
                  $this->postCode= $value;//do not forget validation before set
                 break;
             default :
                die("Error : property does not exist");
                break;
        }
    }

    public function __get($field)
    {
        switch($field){
             case "siteName":
                 return $this->siteName;
                 break;
             case "siteID":
                 return $this->siteID;
                 break;
             case "Location":
                 return $this->Location;
                 break;
             case "postCode":
                 return $this->postCode;
                 break;
             default :
                die("Error : property does not exist");
                break;
        }
    }

    function addSite()
    {
        //use "insert SQL" to store new added site info to DB
        $insertSQL = "INSERT INTO site 
(siteName, location, postcode) 
                      VALUES ('".$this->siteName."', '".$this->Location."', '".$this->postCode."')";

 //after Exequte
        if(!$rs)
        {
            return false;
            die();
        }
        $this->siteID = $rs->insertID;//it depends on your ORM or db connection

        return true;
    }


    function getSiteName(){

        $selectSiteName = "SELECT siteName FROM site WHERE siteID =". $this->SiteID;
       //after Exequte
        if(!$rs)
        {
            return false;
            die();
        }
        $this->siteName = $rs->field['siteName'];//it depends on your ORM or db connection

        return true;
    }

    function getSiteLocation($SiteID){

        selectLocation = "SELECT location FROM site WHERE siteID = ". $this->SiteID;
       //after Exequte
        if(!$rs)
        {
            return false;
            die();
        }
        $this->Locattion= $rs->field['location'];//it depends on your ORM or db connection

        return true;
    }

    function getPostCode($SiteID){

        selectPostcode = "SELECT postcode FROM site WHERE siteID = ". $this->SiteID;
       //after Exequte

        if(!$rs)
        {
            return false;
            die();
        }
        $this->postCode= $rs->field['postcode '];//it depends on your ORM or db connection

        return true;
    }
}

$obj = new Sites();
$obj->siteName = $_POTS['siteName'];//also you can validate your data here before send it to class
$obj->Location = $_POTS['Location '];//also you can validate your data here before send it to class
$obj->postCode = $_POTS['postCode '];//also you can validate your data here before send it to class

$rs = $obj->addSite();
if($rs)
{
    echo "Siet Name : ".$obj->siteName."<br>";
    echo "Location : ".$obj->Location."<br>";
    echo "Post Code : ".$obj->postCode."<br>";
}
else
{
     echo "Error : site info was not added";
}

?>

2- It's really depends on your DB design(you can make siteName uniqe)

3- sure you can define all these functions in this class

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜