We help IT Professionals succeed at work.

creating an instance of a class inside a class

rgb192
rgb192 asked
on
416 Views
Last Modified: 2014-05-10
followup question to:

https://www.experts-exchange.com/Programming/Languages/Scripting/PHP/Q_28423145.html#a40052859



getInstance method returns an object. The important thing is that it can return different types of object based on the extension of the file name given


can you give examples of an instance of a class created in the class
most tutorials teach objects outside class
Comment
Watch Question

Most Valuable Expert 2011
Author of the Year 2014

Commented:
This is generally what is referred to as the Factory Pattern.
http://en.wikipedia.org/wiki/Factory_method_pattern
http://www.phptherightway.com/pages/Design-Patterns.html (Very Good Site, BTW)
http://coderoncode.com/2014/01/19/design-patterns-php-factories.html (Have not read it all, but it looks good)

Author

Commented:
<?php
class ShopProduct {
    private $title;
    private $producerMainName;
    private $producerFirstName;
    protected $price;
    private $discount = 0; 
    private $id = 0;
    
    public function __construct(   $title, $firstName, 
                            $mainName, $price ) { 
        $this->title             = $title;
        $this->producerFirstName = $firstName;
        $this->producerMainName  = $mainName;
        $this->price             = $price;
    }

    public function setID( $id ) {
        $this->id = $id;
    }

    public function getProducerFirstName() {
        return $this->producerFirstName;
    }

    public function getProducerMainName() {
        return $this->producerMainName;
    }

    public function setDiscount( $num ) {
        $this->discount=$num;
    }

    public function getDiscount() {
        return $this->discount;
    }
    
    public function getTitle() {
        return $this->title;
    }

    public function getPrice() {
        return ($this->price - $this->discount);
    }

    public function getProducer() {
        return "{$this->producerFirstName}".
               " {$this->producerMainName}";
    }

    function getSummaryLine() {
        $base  = "Item: $this->title ( $this->producerMainName, ";
        $base .= "$this->producerFirstName )"; 
        return $base;
    }

    public static function getInstance( $id, PDO $pdo ) {
        $query = "select * from products where id='$id'";
        $stmt = $pdo->prepare("select * from products where id=?");
        $result = $stmt->execute( array( $id ) );
        $row = $stmt->fetch( );
        if ( empty( $row ) ) { return null; }

        if ( $row['type'] == "book" ) {
            $product = new BookProduct( 
                                    $row['title'], 
                                    $row['firstname'], $row['mainname'], 
                                    $row['price'], $row['numpages'] ); 
        } else if ( $row['type'] == "cd" ) {
            $product = new CdProduct(
                                    $row['title'], 
                                    $row['firstname'], $row['mainname'], 
                                    $row['price'], $row['playlength'] ); 
        } else {
            $product = new ShopProduct(     
                                    $row['title'], 
                                    $row['firstname'], $row['mainname'], 
                                    $row['price'] ); 
        }
        $product->setId(            $row['id'] );
        $product->setDiscount(      $row['discount'] );
        return $product;
    }
}

class CdProduct extends ShopProduct {
    private $playLength = 0;

    public function __construct(   $title, $firstName, 
                            $mainName, $price, $playLength ) { 
        parent::__construct(    $title, $firstName, 
                                $mainName, $price );
        $this->playLength = $playLength;
    }

    public function getPlayLength() {
        return $this->playLength;
    }

    function getSummaryLine() {
        $base = parent::getSummaryLine();
        $base .= ": playing time - $this->playLength";
        return $base;
    }
 
}

class BookProduct extends ShopProduct {
    private $numPages = 0;

    public function __construct(   $title, $firstName, 
                            $mainName, $price, $numPages ) { 
        parent::__construct(    $title, $firstName, 
                                $mainName, $price );
        $this->numPages = $numPages;
    }

    public function getNumberOfPages() {
        return $this->numPages;
    }
   
    function getSummaryLine() {
        $base = parent::getSummaryLine();
        $base .= ": page count - $this->numPages";
        return $base;
    }

    public function getPrice() {
        return $this->price;
    }
}

require_once("generate_product_pdo.php");
$pdo = getPDO();
$obj = ShopProduct::getInstance( 1, $pdo );
print_r( $obj );
$obj = ShopProduct::getInstance( 2, $pdo );
print_r( $obj );
$obj = ShopProduct::getInstance( 3, $pdo );
print_r( $obj );
?>

Open in new window


is this factory pattern because line64-79 creates (is creates the same as returns???) a new object based upon column in a row $row['type']

Commented:
hello, to your "is this factory pattern because line64-79 creates", the short answer is "YES", , but in programming and certainly PHP code work, there really is not just ONE way to have or use a "Factory" Class object, that Changes the functioning of your Class object according to an input or database SELECT. many times the Class object will change in small ways from inputs, and most will not say that's a Factory change, and sometimes there can be Large Changes in object functioning from inputs or DB SELECT, and some may NOT call is a Factory change, and others may say that it IS a Factory change, it sometime depends on the degree of change, but if you have a DIFFERENT object class produced as your example -
      $product = new BookProduct()
      $product = new CdProduct()
      $product = new ShopProduct()

then that would by most be called a "factory pattern", but trying to name a pattern, may not be much help to a code writer, if he does not understand how and why to write adaptable (changing) code that can adjust to different web pages and code inputs, this is the reason that a "Factory" Class is used, to prevent writing code for 3 different Classes, and write One Class that can adapt and change to three different functioning from an input.

Author

Commented:
i do not understand how this is a factory pattern:
      $product = new BookProduct()
      $product = new CdProduct()
      $product = new ShopProduct()
Most Valuable Expert 2011
Author of the Year 2014

Commented:
i do not understand how this is a factory pattern:
      $product = new BookProduct()
      $product = new CdProduct()
      $product = new ShopProduct()
I think that's kind of the opposite of a Factory pattern.  Please see the explanation given here.  Now that I have read it all, I think it's a great example showing how and when to use Factory.
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION
Most Valuable Expert 2011
Author of the Year 2014
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
"We can define a factory as a simple design pattern that give us a convenient way to instantiate objects. A factory is capable of creating different types of objects without necessarily knowing what type of object is actually being created."

Do you have an Idea or understanding of writing a Class code that can be adaptable (maybe a factory) and change from the web page inputs, to be a way to make better code?

For the sake of argument, let's imagine that every single product has its own unique class. So we would have something like this:  (many classes)


thanks for factory infomation

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.