Search code examples
c++ooptraits

C++ use traits like in PHP


I am searching a solution how I can define reusable code in C++ like traits in PHP.

Description of the problem: I have three classes (Class, Customer, Admin) and each class must sometimes perform the same action like inserting a new child, adding a new address or adding a new class (same with update and remove action). I want to avoid too develop these functions in every class again.

Further more I would be very nice if these functions are separated from the class "product_name". I don't want to write all these functions into the class "product_name" or "product", because otherwise the class becomes too confusing for too many functions.

Edit
The name of the class "product_name" is a placeholder for my product. At the moment I don't know the name of my product :). And the parent class "product" is a collection point for all products that I would like to develop in the future. I created this class, because I want to use Single-Sign-On and the same user database... So I must develop these parts only once!

Class Diagram of my wish: enter image description here


Solution

  • C++ is differ from the PHP in many aspects. This is how you can design your domain driven DAO in C++.

    This example uses POCO library for database connectivity. You can use any another library for the same propose.

    enum class Role {
       ADMIN,
       CUSTOMER,
       SCHOOL_ACCOUNT
    }
    
    class User {
    protected:
      constexpr User(Role role) noexcept:
        role_(role)
      {}
    public:
      User(const User&) = delete;
      User& operator=(const User&) = delete; 
      Role role() const noexcept {
       return role_;
      }
      virtual const char* id() const = 0;
      virtual ~User() = 0;
    private:
      Role role_;
    };
    
    User::~User() 
    {} 
    
    class MyIDGenerator {
    public:
      static std::string generate() {
        static POCO::UUIDGenerator gen;
        return gen.create().toString();
      }
    };
    
    class Customer final: public User  { 
    public:
        Customer() noexcept:
           User(Role.CUSTOMER),
           id_(  MyIDGenerator::generate() ) 
        {} 
        virtual const char* id() const override
        {
          return id_.data();
        }
        virtual ~Customer() override
        {}
    private:
       std::string id_;
    }
    ...
    // define your Admin and School
    ...
    class Product {
     public:
     Product():
       id_( MyIDGenerator::generate() )
     {} 
     void insertUser(const User* user, const Poco::Data::Session& session) {
      // execute your SQL hire i.e. something like
      POCO::Data::Statement insert(session);
      insert << "insert into product_allowed_user values(?,?)" << use(id_) << use(user->id());
      insert.execute(); 
     }
     private:
       std::string id_;
    }