Is it possible in PHP 5 to have an interface that has private / protected methods?
Right now I have:
interface iService
{
private method1();
}
As stated, interfaces can only define the publicly visible methods. I wanted to show an example of how protected methods can be handled. To impose the use of specific protected methods, it is possible to create an abstract class that implements the interface.
This especially makes sense if the abstract class can already handle some of the workload, to simplify the actual implementation. Here for example, an abstract class takes care of instantiating the result object, which is always needed:
First off, the interface.
interface iService
{
/**
* The method expects an instance of ServiceResult to be returned.
* @return ServiceResult
*/
public function doSomething();
}
The abstract class then defines the internal methods structure:
abstract class AbstractService implements iService
{
public function doSomething()
{
// prepare the result instance, so extending classes
// do not have to do it manually themselves.
$result = new ServiceResult();
$this->process($result);
return $result;
}
/**
* Force all classes that extend this to implement
* this method.
*
* @param ServiceResult $result
*/
abstract protected function process($result);
}
The class that does the actual implementation automatically inherits the interface from the abstact class, and only needs to implement the protected method.
class ExampleService extends AbstractService
{
protected function process($result)
{
$result->setSuccess('All done');
}
}
This way the interface fulfills the public contract, and through the AbstractService
class, the internal contract is fulfilled. The application only needs to enforce the use of the AbstractService
class wherever applicable.