|  | Posted by Malcolm Dew-Jones on 06/23/07 00:02 
grossespinne@gmail.com wrote:: Hi everybody!
 : I have been thinking over the following problem:
 : there are three classes: PageBase, which is the base class, PageA and
 : PageB which are the subclasses of PageBase.
 : In the index.php file I have a variable which I like to hold either an
 : instance of PageA or PageB depending on the query string that is
 : passed to index.php (e.g: if I get the query index.php?content=a, I
 : need an instance of PageA, but if I get the query: index.php?
 : content=b, an instance of PageB is needed)
 
 : Until now I found two solutions, but I am not satisfied with either of
 : them:
 : - use a switch structure
 : - or use eval:
 
 : $pageType = isset($_GET["page"]) ? $_GET["page"] : "PageBase";
 : $thePage = eval("return new $pageType();");
 
 : My question is whether a more object-oriented way exists to solve the
 : problem.
 
 No, that's one of the dirty little secrets of OOPs programming.
 Somewhere you have to do what you do above, either something like a
 switch, if/then/else, or as in your case something like an eval.
 
 (BTW: I would recommend a switch (or if/then/else) over eval because that
 prevents any chance of code injection.  What if "page" is set to a string
 like "system('rm /*');"  which probably wouldn't run in your code, but
 shows what I am getting at.  You don't want to put that in your eval().)
 
 
 However you normally hide the dirty details in a "factory" class that
 returns an instance of the _base_ class.  (In php that won't make much
 difference, as long as each class implements the same methods then all is
 ok, in a language like Java it must explicitly be the base class.)
 
 (my syntax correct! I haven't used php for a little while).
 
 $thePage = PageFactory->createPage( $pageType );
 
 later, when you say
 
 $thePage->someMethod($var1,$vars) ;
 
 then either
 PageA->someMethod
 runs or
 PageB->someMethod
 runs.
 
 
 PageFactory is a class that you create.  In this case it has one static
 method that returns PageBase.  The code is something like (my syntax is
 not valid php today)
 
 function createPage ( $type ) returns PageBase
 
 if    ($type = 'A') return (PageBase) new PageA();
 
 elsif ($type = 'B') return (PageBase) new PageB();
 
 else  die "$type is not a known type of page";
 
 end function
  Navigation: [Reply to this message] |