当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Are non-implemented abstract methods a design flaw?

问题描述:

Here is an example of my class structure for a data mapping pattern (simplified). Notice that the save and find methods are technically implemented in the concrete class, but do not do anything yet. What alternatives are there to avoid this? One option I am currently using is an abstract DataMapperAbstract class that implements the interface, throws an exception for every method, then all concrete data mappers only have to implement the functions they use - it just smells bad. Personally, I have thought of creating a separate interface for each method (DataMapper_FindInterface, DataMapper_SaveInterface, DataMapper_DeleteInterface, etc.) but it seems a bit smelly.

 interface DataMapperInterface

{

public function find($params);

public function save($object);

public function delete($object);

}

class DataMapper_User implements DataMapperInterface

{

public function find($params)

{

//Execute code to retrieve data from data source

return someDataRetrievalMethod($params);

}

public function save($object)

{

throw new Exception('Method not yet implemented.');

}

public function delete($object)

{

throw new Exception('Method not yet implemented.');

}

}

网友答案:

As long as you are not in the class that has al methods implement, make the class abstract.

Abstract classes can not be instantiated, and there must be another class thats extends the abstract class with a implementation.

So your code so far would look like this:

    interface DataMapperInterface
    {
            public function find($params);
            public function save($object);
            public function delete($object);
    }

    abstract class DataMapper_User implements DataMapperInterface
    {                               
            public function find($params)
            {                       
                    //Execute code to retrieve data from data source
                    return someDataRetrievalMethod($params);
            }

    }
分享给朋友:
您可能感兴趣的文章:
随机阅读: