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 7974867
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T08:30:09+00:00 2026-06-04T08:30:09+00:00

I am trying to create a simple factory pattern demo in PHP. I am

  • 0

I am trying to create a simple factory pattern demo in PHP. I am not sure if my codes are the best practice. It seems that I have some duplicated codes but I am not sure how to improve it. Basically, I want to create 3 types of accounts (basic, premium and vip). Please advise. Thanks a lot.

abstract class

abstract class User {

    function __construct() {
        $this->db= new Database('mysql','localhost','mvcdb','root','');
    }

    abstract function checkUser();

    function showAccountCredit(){
        return $this->credits;
    }
    function getUserName(){
        return $this->username;
    }


}

I have 3 different user account types:

Basic Account

class BasicUser extends User {

    function __construct($username) {
        parent::__construct();
        $this->username=$username;
        $this->credit='10';
        $this->accountType='Basic Account';

        $data=$this->checkUser();

        if(!empty($data)){
            echo 'The username: '.$this->username.' already exists<br>';
            return false;
        }

        $array=array('username'=>$this->username, 'password'=>'password','credit'=> $this->credit,'accountType'=>$this->accountType);
        $this->db->insert('user',$array);

    }


     function checkUser(){

        $array=array(':username'=>$this->username);
        $results=$this->db->select('SELECT * FROM USER WHERE username=:username',$array);
        if(!empty($results)){
        $this->credit=$results[0]['credit'];
        $this->accountType=$results[0]['accountType'];
        }

        return $results;

    }

    function showAccountCredit() {
        echo 'Username: '.$this->username.'<br>';
        echo 'Account Credit: '.$this->credit.'<br>';
        echo 'Account Type: '.$this->accountType;
    }

}

Premium Account

class PremiumUser extends User {

    function __construct($username) {
        parent::__construct();
        $this->username=$username;
        $this->credit='100';
        $this->accountType='Premium Account';

        $data=$this->checkUser();

        if(!empty($data)){
            echo 'The username: '.$this->username.' already exists<br>';
            return false;
        }

        $array=array('username'=>$this->username, 'password'=>'password','credit'=> $this-                   >credit,'accountType'=>$this->accountType);
        $this->db->insert('user',$array);

    }


     function checkUser(){

        $array=array(':username'=>$this->username);
        $results=$this->db->select('SELECT * FROM USER WHERE username=:username',$array);
        if(!empty($results)){
        $this->credit=$results[0]['credit'];
        $this->accountType=$results[0]['accountType'];
        }

        return $results;

    }

    function showAccountCredit() {
        echo 'Username: '.$this->username.'<br>';
        echo 'Account Credit: '.$this->credit.'<br>';
        echo 'Account Type: '.$this->accountType.'<br>';
    }

}

VIP account:

class VipUser extends User {

    function __construct($username) {
        parent::__construct();
        $this->username=$username;
        $this->credit='1000';
        $this->accountType='VIP Account';

        $data=$this->checkUser();

        if(!empty($data)){
            echo 'The username: '.$this->username.' already exists<br>';
            return false;
        }

        $array=array('username'=>$this->username, 'password'=>'password','credit'=> $this->credit,'accountType'=>$this->accountType);
        $this->db->insert('user',$array);

    }


     function checkUser(){

        $array=array(':username'=>$this->username);
        $results=$this->db->select('SELECT * FROM USER WHERE username=:username',$array);
        if(!empty($results)){
        $this->credit=$results[0]['credit'];
        $this->accountType=$results[0]['accountType'];
        }

        return $results;

    }

    function showAccountCredit() {
        echo 'Username: '.$this->username.'<br>';
        echo 'Account Credit: '.$this->credit.'<br>';
        echo 'Account Type: '.$this->accountType;
    }

}

UserFactory class

class UserFactory {

    static function create($username,$accountType){

        $accountType = strtolower($accountType);

        switch($accountType){
        case 'basic': return new BasicUser($username);
        case 'premium':return new PremiumUser($username);
        case 'vip': return new VipUser($username);
        default :return new BasicUser($username);
        }
    }

index.php

$user1= UserFactory::create('Jerry', 'Vip');
$user1->showAccountCredit();


$user2= UserFactory::create('Bob', 'Basic');
$user2->showAccountCredit();


$user3= UserFactory::create('Betty', 'premium');
$user3->showAccountCredit();
  • 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-06-04T08:30:11+00:00Added an answer on June 4, 2026 at 8:30 am

    Instead of having 3 different implementations of user, consider 3 different implementations of “UserType”. Separating responsibilities and composing objects together. Here’s another pattern in action, called strategy.

    function showAccountCredit(){
      return $this->type->showAccountCredit();
    }
    

    New class, UserType represents special behavior, User would then contain rest of generic stuff, reducing duplication you’ve described (or at least most of it)

    Factory on the other hand can be used for loading objects from db:

    class Loader{
      private $userTypeFactory;
    
      public function loadUser($id){
        $userRow = $db->loadRow();
        ...
    
        $userType = $userTypeFactory->$userRow["type"]();
        return new User($userType);
      }
    }
    
    class UserTypeFactory{
      public function vip(){
        return new VipUserType();
      }
    
      public function premium(){
        return new PremiumUser();
      }
    }
    

    You can go even step further and introduce IoC framework. Have a look on symfony2. Oh, and please dont use switch, rather do it like I did, polymorphism, dynamic calls.


    EDIT:

    Strategy == wrapped behavior. For example if you were checking user rights for seeing premium content, this is how it would usually look like:

    class PagesController{
      ...
    
      public function showPage($id){
        ...
        if ($user->type == "premium" || $user->type == "vip"){
          ...
        }
        else if ($user->type == "credit"){
          $user->credits--;
          updateUser();
        }
        else{
          die("You do not have permissions to see this content...");
        }
    
        ... //render page
      }
    }
    

    And here’s how it could look like using “strategy”:

    class PagesController{
      ...
      public function showPage($id){
        $page = ...;
    
        $user->pageRequested($page);
    
        //render page
      }
    }
    
    class User{
      private $userType;
    
      public function pageRequested($page){
        $this->userType->userRequestedPage($user, $page);
      }
    }
    
    class VipUserType{
      public function userRequestedPage($user, $page){
        //do nothing
      }
    }
    
    class PremiumUserType{
      public function userRequestedPage($user, $page){
        //do nothing
      }
    }
    
    class BasicUserType{
      public function userRequestedPage($user, $page){
        throw new Exception("You cant access this page");
      }
    }
    
    class CreditUserType{
      public function userRequestedPage($user, $page){
        $user->credit--;
        $user->save();
      }
    }
    

    This way, everything what’s related to userType is separated, it’s easy to add new types without risk of breaking existing types.

    BTW: This is nothing more than just plain old polymorphism. Strategy is just another shiny word for OOP essentials, like most of patterns. Do not waste time thinking about patterns, they’re good for inspiration however you’ll gain much more experience from real OOP, have a look on smalltalk – http://www.pharo-project.org/home

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

Sidebar

Related Questions

I'm trying to create a simple search page, but I'm not 100% sure how
I'm trying to create a really simple Factory Method design pattern example in Java.
Im trying to create a simple input box with form validation, but im not
I am trying to create a simple Automator droplet that will take the style.less
I have this abstract factory pattern that I use in as3 that I am
Trying to get a simple PHP/Zend Framework setup to create a SQLite databse and
I am trying to create a simple Hit Counter using Kohana3 and PHP. But
I'm studying webrat and cucumber and trying to create simple example. Here is my
Im trying to create a simple pan and zoom app using silverlight 4, but
I'm trying to create a simple Add-On for SQL Server 2008; it is simply

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.