Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7622513
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 31, 20262026-05-31T04:28:23+00:00 2026-05-31T04:28:23+00:00

One can accomplish same thing using different tools. So have I in examples below.

  • 0

One can accomplish same thing using different tools.
So have I in examples below.

One shows use of interface/polymorphism (source: nettuts – I think). Another straightforward class interactions (mine) – which shows some polymorphism as well (via call_tool()).

Would you tell me, which would you consider to be a better way.

Which is safer, more stable, tamper resistant, future proof (afa code development is concerned).

Please scrutinise scope/visibility used in both.

Your general recommendations, as which is best coding practice.

INTERFACE:

class poly_base_Article {

    public $title;
    public $author;
    public $date;
    public $category;

    public function __construct($title, $author, $date, $category = 0, $type = 'json') {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;

        $this->type = $type;
    }

    public function call_tool() {
        $class = 'poly_writer_' . $this->type . 'Writer';
        if (class_exists($class)) {
            return new $class;
        } else {
            throw new Exception("unsupported format: " . $this->type);
        }
    }

    public function write(poly_writer_Writer $writer) {
        return $writer->write($this);
    }

}

interface poly_writer_Writer {

    public function write(poly_base_Article $obj);
}

class poly_writer_xmlWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {
        $ret = '';
        $ret .= '' . $obj->title . '';
        $ret .= '' . $obj->author . '';
        $ret .= '' . $obj->date . '';
        $ret .= '' . $obj->category . '';
        $ret .= '';
        return $ret;
    }

}

class poly_writer_jsonWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {
        $array = array('article' => $obj);
        return json_encode($array);
    }

}

$article = new poly_base_Article('Polymorphism', 'Steve', time(), 0, $_GET['format']);
echo $article->write($article->call_tool());

NON-INTERFACE

class npoly_base_Article {

    public $title;
    public $author;
    public $date;
    public $category;

    public function __construct($title, $author, $date, $category = 0, $type = 'json') {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;
        $this->type = $type; //encoding type - default:json
    }

    public function call_tool() {
        //call tool function if exist
        $class = 'npoly_writer_' . $this->type . 'Writer';
        if (class_exists($class)) {
            $cls = new $class;
            return $cls->write($this);
        } else {
            throw new Exception("unsupported format: " . $this->type);
        }
    }

}

class npoly_writer_jsonWriter {

    public function write(npoly_base_Article $obj) {
        $array = array('article' => $obj);
        return json_encode($array);
    }

}

class npoly_writer_xmlWriter {

    public function write(poly_base_Article $obj) {
        $ret = '';
        $ret .= '' . $obj->title . '';
        $ret .= '' . $obj->author . '';
        $ret .= '' . $obj->date . '';
        $ret .= '' . $obj->category . '';
        $ret .= '';
        return $ret;
    }

}

$article = new npoly_base_Article('nPolymorphism', 'Steve', time(), 0, $_GET['format']);
echo$article->call_tool();

MikeSW code (if I get it right)

 class poly_base_Article {

    private $title;
    private $author;
    private $date;
    private $category;

    public function __construct($title, $author, $date, $category = 0) {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;
    }

    public function setTitle($title) {
        return $this->title = $title;
    }

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

    public function getAuthor() {
        return $this->author;
    }

    public function getDate() {
        return $this->date;
    }

    public function getCategory() {
        return $this->category;
    }


}

interface poly_writer_Writer {

    public function write(poly_base_Article $obj);
}

class poly_writer_xmlWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {

        $ret = '';
        $ret .= '' . $obj->getTitle() . '';
        $ret .= '' . $obj->getAuthor() . '';
        $ret .= '' . $obj->getDate() . '';
        $ret .= '' . $obj->getCategory() . '';
        $ret .= '';
        return $ret;
    }

}

class poly_writer_jsonWriter implements poly_writer_Writer {

    public function write(poly_base_Article $obj) {
        //array replacement
        //$obj_array = array('title' => $obj->getTitle(), 'author' => $obj->getAuthor(), 'date' => $obj->getDate(), 'category' => $obj->getCategory());
        //$array = array('article' => $obj_array);

        $array = array('article' => $obj); //$obj arrives empty
        return json_encode($array);
    }

}

class WriterFactory {

    public static function GetWriter($type='json') {
        switch ($type) {
            case 'json':
            case 'xml': $class = 'poly_writer_' . $type . 'Writer';
                return new $class;
                break;
            default: throw new Exception("unsupported format: " . $type);
        }
    }

}

$article = new poly_base_Article('nPolymorphism', 'Steve', time(), 0);
$writer=WriterFactory::GetWriter($_GET['format']);

echo $writer->write($article);
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-31T04:28:25+00:00Added an answer on May 31, 2026 at 4:28 am

    Ahem, your approaches have some flaws no matter what version. First thing, the poly_base_Article exposes the fields which breaks encapsulation and kinda defeats the purpose of using OOP in the first place.

    Next, you have a fine injection there via the $_GET parameter. THe proper way to do the class should be like that

     class poly_base_Article {
    
    private $title;
    private $author;
    private $date;
    private $category;
    
    public function __construct($title, $author, $date, $category = 0) {
        $this->title = $title;
        $this->author = $author;
        $this->date = $date;
        $this->category = $category;
    
    }
    
     public function getTitle() { return $this->title;}
     //...other getters defined here...
    
       public function AsArray()
         { 
              return (array) $this;
         }
    
    //this could be removed
    public function write(poly_writer_Writer $writer) {
        return $writer->write($this);
    }
    }
    

    The write method doesn’t seem to be required though, you just tell the writer to write the object directly.

    The *call_tool* method should belong to a service or as a factory method to create an instance of poly_writer_Writer (btw, you should change the naming of the classes and interface to something more natural), something like this

    class WriterFactory
     {
         public static function GetWriter($type='json')
          {
             switch($type)
             {
                case 'json'
                case 'xml': $class= 'poly_writer_' . $type . 'Writer'; 
                 return new $class;
                  break;
                 default: throw new Exception("unsupported format: " . $type);
               }
            }
     }
    
    
      $article = new poly_base_Article('nPolymorphism', 'Steve', time(), 0);
       $writer=WriterFactory::GetWriter(, $_GET['format']);
     echo $writer->write($article);
    

    Which is safer, more stable, tamper resistant, future proof (afa code development is concerned).

    That depends only on the developer skill and discipline. In this particualr case, the code I’ve written is the safer, tamper resistant and future proof 😛

    Update
    Indeed, I forgot to put getters in the poly_base_Article, I’ve added them now. Since you’re doing serialization, the article shouldn’t know about it, as it’s not his responsability (it’s part of the infrastructure layer) so the write method is not required at all, but that’s a specific case here (in the everything depends on the context).

    The WriterFactory is basically the factory pattern which creates an instance of the writer and returns an abstraction – that’s the polymorphism where the interface is useful. This approach makes it very easy to add new implementations of the interface and also to guard against code injection.The switch is to check that only the valid values of $type are permitted. You might validate the $type in other places but this is the only place which should handle everything related to creating writers. Even if you want to validate outside it you just create a static method in the WriterFactory which will return true/false and use than.

    About interfaces being a fad… using interfaces is how OOP should be done. It’s a best practice to program against an abstraction and the interfaces are the ‘best’ abstraction. To put it bluntly: if interfaces are a fad, then OOP is a fad.

    About your second example, well the first too, the method which creates the writer should not be there in the first place as it couples the creation of the writer to the article and those 2 have pretty much nothing in common. It’s a breaking of the SRP (Single Responsability Principle).

    In this particular case, once you are doing the creation factory in a separate class then you pretty much don’t care about the interfaces, however that because the usage is very simplistic here and you’re using PHP or a loosely type language. If you would pass the writer as a dependency then it will help to pass around the interface and not an actual implementation (like you did in the first example). It’s very helpful to know what type you’re passing around.

    Also In a language like C#, you would have a return type and then, as an optimum usage, you would return it as the interface type (C# supports dynamic types which let’s say behave a bit like in PHP so you can return dynamic and not care, but that comes with a performance penalty and if the type returned doesn’t have the method invoked it will throw an exception)

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

One can remove all calls to printf() using #define printf . What if I
How could I accomplish row level security using Zend_Db_Select ? I can think of
One can create an anonymous object that is initialized through constructor parameters, such as
One can tag files and folders with a color in the Mac OS X
Where one can learn more about VectorScript (the Pascal-like programming languaged built into NNA
If one can prevent subclassing by declaring private constructor in the base class, why
Any one can share the mainfest.xml. How to set it? then can remove the
How can one implement the fisheye lens effect illustrated in that image: One can
In bash one can escape arguments that contain whitespace. foo a string This also
In SQL one can write a query that searches for a name of a

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.