PHP naming conventions about abstract classes and interfaces - php

Should an abstract class always be prefixed with Abstract and suffixed with Interface (when it's an interface)? Is there any standard naming convention, similar to PSR-0 for folder structure/namespaces, but for classes?
It seems redundant as the language has literal keywords for this very purpose.
abstract class AbstractFoo {}
interface InterfaceFoo {}
trait TraitFoo {}

The PHP-FIG project indeed suggests a naming convention via the PSR Naming Convention "ByLaw" https://www.php-fig.org/bylaws/psr-naming-conventions/
It states:
Interfaces MUST be suffixed by Interface: e.g. Psr\Foo\BarInterface
Abstract classes MUST be prefixed by Abstract: e.g. Psr\Foo\AbstractBar
Traits MUST be suffixed by Trait: e.g. Psr\Foo\BarTrait
These conventions are generally followed in packages

Although there's not any convention, I think it is a good practice using Abstract prefix and Interface suffix for respective components. It helps to understand better the code at a glance, IMO.

There isn't a convention for this; especially in PHP. This can all be organized however you'd like.
With the additions of namespaces in PHP 5.3, I don't see the need to add Abstract or Interface prefixes/suffixes to the actual class names.
Just name things as they are!

Going against most of the other answers, I would suggest that it's better not to add a prefix or postfix to the class. The language has literal keywords such as abstract, interface, class, final for this purpose.
The following actually breaks clean code principals:
abstract class AbstractPerson
{
// ...
}
Similar thinking to "comments are generally bad, as it suggests the code is not easily readable". If your classes, inheritance and their contracts are engineered in a clear and readable fashion that makes sense, there is no need for prefixing.
Behavioural design
It's usually possible to name things in a manner that reflects their behaviour. For example in a logging subsystem:
interface Loggable
{
public function getLog(): string;
}
trait WritesLogs
{
public function writeLog(): void
{
file_put_contents("logs.txt", $this->getLog());
}
}
abstract class Event implements Loggable
{
use WritesLogs;
public function asLog(): string
{
return "{$this->getName()} at {$this->created_at}";
}
abstract public function getName(): string;
}
class FooCreated extends Event
{
public function getName(): string
{
return 'Foo was created';
}
}

Naming your abstract classes and interface by using:
Abstract*
*Interface
Will keep your codebase clean, nice and obvious to your team what are the prototypes, what are the contracts and what are the concrete implementations.
Naming conventions are here to increase our productivity in any circumstance, so "name as you like" is far from good idea.
Even though FIG group does not propose naming convention for abstract classes and interfaces - if you examine major open source PHP projects, you will see that almost all of them uses this convention.

Conventions are what you see them like: the language itself doesn’t force any conventions other than those that makes the parser able to read your code. Basically, you should have conventions set up on your own for a particular project, or better, for all of your projects. However, working in teams of different people could lead to conventions not being followed, it really depends on the programmers.
From my experience, I would suggest following something like "design-by-contract". Name your contracts (interfaces) like you would name your implementation class, and then give your implementation a more specific name (or fallback to MyContractNameImpl, known mostly from Java I guess). Also, many modern IDEs know whether your class is an interface or abstract, so there is really no need to put that in it’s name. I also find contracts named like "IMyContract" not really good, for the same reasons.

Related

If utility class is an anti pattern, what is the alternatives in PHP?

I am trying to build my own MVC framework (of course to learn it better) by following latest OOP design pattern. I was wondering, what is the best practice for placing repeatable codes (which are used to stay in the utility classes as static methods, which is consider not a good patterns).
For example, we want to traverse an multi dimensional array using dot separated string, and I have to utilize this algorithm in several classes (which are subclasses from other base classes). How can I do that without using utility class and without repeating the same code multiple times?
If those are utility functions, then define them as such in a separate namespace. Something akin to
<?php
namespace Utils;
function array_query($array, $query) {
// code for traversing the array
}
Put them in one or multiple files and you will be fine. Just remember to include that file in the boostrap stage of your app.
Bottom line: stop abusing static classes, we have namespaces for that sh*t now.
But, not all of what you think of as "utility functions" are actually. Some of the code, if you start using OOP code, should go in the associated classes. For example "email validation" should not go in a "utility function" but in a class:
class EmailAddress {
private $emailAddress;
public function __construct($emailAddress) {
$this->assertValidEmailAddress($emailAddress);
$this->emailAddress = $emailAddress;
}
private function assertValidEmailAddress($emailAddress) {
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
throw new DomainException("Not an email address");
}
}
public function __toString() {
return $this->emailAddress;
}
}
And these kind of repeated "domain logic" fragments should go in separated entities, which then you can type-hint for other classes. Then you utilize it somewhere as:
public function register(EmailAddress $email, SafePassword $password): User
{
// your user registration logic
}
This way various services of yours can perform activities and you use try-catch for improved validation.
P.S.
You might need to take a hard look at what you are doing. That dotted access utility is neat (I had it too like 10 years ago), but actually is is a "temporary fix" for a deeper problem: you shouldn't be dealing with so deep array, that you need to simplify accessing them.
There's nothing wrong with a utility class, just don't lump all your unrelated utility functions into a single giant class. Separate (and namespace) them by what they do. For example, see Zend Filter or Symfony Filesystem.
Alternatively, if the classes that need this function all have a common parent, you can put the function in the top-most class or abstract.
Or if the classes do not have a common parent, you could create a Trait with a method called extractArrayFromDottedString() or similar.
Laravel does this by defining standalone "helper" functions. CakePHP and Yii do it by defining container utility classes (i.e. "Text" or "Xml") with static methods. Programming languages do similar things (i.e. PHP's implode(), Java's Math.round, C's strcpy, Python's sum(), etc.). Pretty much everything uses either standalone functions or static class methods.
Ultimately, the best choice is subjective. It depends on how you want to structure things. Research common design patterns in PHP, and get a feel for how different frameworks feel in practice. Then pick an approach and stay consistent.
Utility class is an anti pattern
Really not.
In OOP, designing the whole application with utility classes is very probably an anti pattern but defining utility classes wit static methods that provide routine/transverse tasks may make sense.
Not mixing utility methods with methods of existing classes that consume them may also provide a better cohesion and reusability of the utility class and consumer classes.
Of course as alternative you could define a class with instance methods.
This is valid, more verbose but has as advantage to improve the class testability. If you need to mock the invocations or to switch to other implementations for utility methods, instance methods have to be favored.

PHP - if all methods in abstract class are abstract then what is the difference between interface and abstract class

An Abstract Class may and may not have abstract methods but an interface has unimplemented methods only. So what is the difference and advantage of using an interface if my abstract class has all of its methods marked as abstract?
Interfaces and Abstraction
The real power of use can be revealed in huge APIs with massive amount of classes that follow a well-thought flexible structure for future coding. Whether it may happen or not - you never know whether a code will be extended. Interfaces are merely used for semantic reasons. Imagine, you extend a deprecated version of an API and have the job to edit/alter/implement/update/improve/extend/modify the code to bring it up to date, whatever the reason is. You'd end up being frustrated if you did not think forward.
Small APIs can be made without the interfaces and that's where most people think interfaces were unnecessary. But then they lose their flexibility as soon as they become larger. They provide you a contract with classes which reminds you what is needed and to keep the overview. Interfaces must have public methods, if you have protected or private ones, just return them in a public method of a class with interface implemented..
Like you already explained, interfaces demand particular methods to be implemented, abstract classes don't demand it since you most likely extend them anyway. Methods can be re-defined and abstract methods MUST be defined in child classes. Methods mentioned in an interface only tells you that classes that have a contract with an interface must have these defined. It could be multiple interfaces, you don't inherit from them like you would do it with abstract classes.
Think like this way
The logic in it is to predict the future in what you are planning to build. Be it in architecture, infrastructure or mass production in factories. Just like the way you sort items like bookmarks, books, images in a folder. Because you know it would take longer to find a particular image if you didn't sort it. The semantic purpose of abstraction and interface is similar, especially in huge APIs.
An interface reperesents a frame of possibilities and requirements.
An abstraction preserves conceptual information that is relevant in a derived context.
I'll show you a typical structure for a start of an API with simplified contents wherein interfaces and abstract classes have a real point of usage for future extension.
/* Considering, this project will be widely expanded up to huge complexity.
This is a flexible base structure, for developers working in team. Imagine
there could be lots more variation of styles for certain purposes. */
// OOP STRUCT
// You might want to define multiple interfaces to separate the project
interface iString {
// These methods MUST be defined or else the developer receives an error
public function getContent();
public function description($desc);
}
/* Devs might want to add an additional method later on.
Traits are useful for quick use. (optional) */
trait desc {
private $desc;
public function description($desc) {
return $this->desc;
}
}
/* This is the base class for the content which requires a declaration
of methods being described in the interface */
class contents implements iString {
use desc; // use the method defined in a trait
private $str;
public function __construct($str) {
$this->str = $str;
}
public function getContent() {
return $this->str;
}
}
/* Or devs often consider abstract classes as the real base of the whole project/app.
Abstract classes allow the use of methods that can be modified/declared for further use in derived classes.
Interfaces can't do that */
abstract class stylize {
private $str;
// This typehint below makes sure that this value is assigned on interface
public function __construct(iString $str) {
$this->str = $str;
}
public function style() {
return $this->str->getContent();
}
abstract public function getContent();
}
// EXTENDED CLASSES
class bold extends stylize {
// Extended classes have to define abstract methods inherited from an abstract class. Non-abstract methods are not needed.
public function getContent() {
return "<strong>".parent::style()."</strong>";
}
}
class underline extends stylize {
public function getContent() {
return "<u>".parent::style()."</u>";
}
}
class upperCase extends stylize {
public function getContent() {
return strtoupper(parent::style());
}
}
// PROCEDUAL OUTPUT
// A tiny shortcut
$e = function($desc,$str) { echo $desc.": ".$str->getContent()."<br>"; };
// Content being used
$content = new contents('Hello World.');
$e("Normal",$content);
// Content being styled
$bold = new bold($content);
$underline = new underline($content);
$upper = new upperCase($content);
// Renders content with styles
$e("Bold",$bold);
$e("Underline",$underline);
$e("Uppercase",$upper);
Conclusion
Applying styles of text contents as an example is probably not appealing enough. But apart from this, it remains the same - if it does what it should do, then it's done. Like as if I would build an expandable eMail configuration API as a module for a CMS. This structure has a semantic process in proper coding.
Tipps
I'd suggest you to keep learning in small projects with this pattern, even if you think interfaces are not worth it. Keep doing this until you have it inside. My own personal advice for you:
If you think you have no idea where to start and what project to try it on, then try real world examples just follow this logic:
Vehicles (abstract class)
-> Ferrari (extended class)
-> Truck (extended class)
both have wheels (property)
both must be able to drive (method)
they perform a 1mile match race on a street (abstract method)
one is a slowpoke (extended property)
one is red one is blue (extended property)
and later a 3rd one comes and its a train (extended class)
who's going to win (some method)
Instantiate all vehicles and maintain privileges over interface and
abstraction.
...something like this...
Usually, classes containing huge bodies are supposed to be separated in single files + include these + define a namespace. Else wall of code would make you or someone else tired. Use Eclipse, best app for maintaining OOP.
Also, if it fits for your project, use phUML if you have Linux Ubuntu. It generates a graphical diagram for your current build if you have a lot of relating classes.
phUML is an API in PHP based on UML. It is an open-source project which generates any visual schemes for almost any popular programming language. I use it a lot, not just for PHP. Simply clone it at Github or download from dasunhegoda.com and follow installation guide there. This could interest you also: Typehinting on Interfaces
An Abstract Class allows for "partial implementation" (see the template method pattern), but in this case, if all methods are abstract, you don't see that benefit. One other thing you can do is include fields, you're not just limited to methods.
Remember, there's a conceptual difference between an "abstract method" and the contract defined by an interface. An abstract method has to be overridden by a subclass which is done through inheritence implementation. Any polymorphic calls (downcasting) will require one superclass per class or it would hit the diamond inheritance problem. This kind of inheritence based tree structure is typical of OO design.
As a contrast, an interface provides a signature of a contract to fulfil. You can fulfil many interface's needs as long as you retain the signature as there is no question of going back up the class hierarchy to find other implementations. Interfaces don't really rely on polymorphism to do this, it's based on a contract.
The other thing of note is you may have "protected" abstract methods, it makes no sense to do such a thing in an interface (in fact it's illegal to do so).
If an abstract class has all of its methods defined as abstract then you have to define its body in any subclasses and it displays similar behavior as interface.
Benefit :
Using interface instead of abstract class, you can implement more than one interfaces while using abstract class you can only extend one class at a time.
EDIT
Another difference I found about this is abstract class can have constructor while interface can't have.
REF: What is the use of constructor in abstract class in php

PHP. Use of methods in the base class which will be defined in the derived

Is it a good practice to use in the base class a method which will be defined in a derived one? For instance:
abstract class CApplication {
use TSingleton;
protected final function singletonInstanceInit() {
if (php_sapi_name() == 'cli') {
$this->initCLIApp();
}
else {
$this->initWebApp();
}
}
}
abstract class CWebApplication extends CApplication {
protected function initWebApp() { }
}
abstract class CCLIApplication extends CApplication {
protected function initCLIApp() { }
}
AFAIK this is not a good practice.
Inheritance is needed for the purpose of defining new behaviors and new specialized types of objects. Which means that you could/*should* write a base class now and extend it some time late on.
If the base class knows something about the structure of it's derived classes that's somewhat of a contract, the derived classes need to implement some functions in order to work with that base class in which case "design by contract" springs to mind.
If you need to have a certain function in the derived class maybe it should be declared as an abstract function in the base class or as a method in an interface the class implements.
That way it's not unreasonable for the base class to know about methods implemented in the derived classes.
Also AFAIK other stricter languages would not permit this at compiler level. You would really need to do some refactoring to achieve this in c++ or Java something along the lines of what I said above using abstract functions in the base class or interfaces.
What you are talking about is 2 different schools of thought. I've seen ruby developers doing such stuff because they were using mixins (yes lots of gems do that). On other hand if you go and ask a classic Java programmer he won't recommend you doing that. The type of liberty that you are just showing in your code is what only dynamic typed languages give you (Ya I know some heads would nod saying I used CGLib), they are implementable either in a hackish way for static typed languages or they are not used at all.
Long story cut short, if I were you I would look into scenario and decide if I need such black magic for my given task or not? No rule is bad as long as it doesn't hurt the code quality.

Naming abstract classes

Do you think it's a good practice to differentiate abstract from non-abstract classes by giving their name a prefix or a suffix? What are the most common practices when it comes to that?
Here are a few "formats" I've been thinking about:
Foo_Base
Foo_Abstract
Abstract_Foo
Base_Foo
The use of underscores and letter case is irrelevant.
Edit: It seems like the Zend Framework uses a "Abstract" suffix (source).
Do you think it's a good practice to differentiate abstract from non-abstract classes by giving their name a prefix or a suffix?
Unless you're following some convention, I would suggest not to attach this type of meta-data to your class names. Basically it clutters the code with information available elsewhere. To me it resembles hungarian notation which is loathed by many programmers.
Here are a few "formats" I've been thinking about...
If I had to choose, I'd go with AbstractFoo.
According to these PHP Coding Standard you should really avoid _:
Class Names
Use upper case letters as word separators, lower case for the rest of a word
First character in a name is upper case
No underbars ('_')
Justification
Of all the different naming strategies many people found this one the best compromise.
Example
class NameOneTwo
class Name
Probably not with a direct reference to a (1) derived class...
In a real situation there usually is a domain-specific collective name available.
But when there isn't I usually go with something like BaseViewModel
Foo_Abstract or Abstract_Foo is a bad idea if you plan to use namespaces, as you will have Foo\Abstract, which is invalid.
I think it is bad practice to name variables/functions/classes based on the type that it represents. int myInt is good for coding a quick example (perhaps in a classroom setting) but thats about it.
abstract class AbstractClass is too redundant and annoying to read. Let your programs/code say a lot in a concise way, and speak for themselves. From reading the definition I know its an abstract class I shouldn't need to be reminded in the name of the class. Focus on what purpose the class has in reference to the problem instead of what type of class it is.
This is the gist of things I got from Clean Code
If you describe the project I can suggest good names that aren't redundant.
Why don't you actually want to specify a class to be abstract then you should use the abstract keyword in PHP
abstract class MyClass
{
//**
}
If you want a way to check for abstract classes such as logical checks then you should create an interface like so:
interface IAbstract
{
}
and then declare the class with it
abstract class MyClass implements IAbstract
{
//**
}
and then you can check like so:
if(MyClass instanceof IAbstract)
{
//Abstract
}
This way you don't need to change your class names to suit the object types.

Is it ever okay to have a class as a collection of methods and no properties?

I'm writing a bunch of generic-but-related functions to be used by different objects. I want to group the functions, but am not sure if I should put them in a class or simply a flat library file.
Treating them like a class doesn't seem right, as there is no one kind of object that will use them and such a class containing all these functions may not necessarily have any properties.
Treating them as a flat library file seems too simple, for lack of a better word.
What is the best practice for this?
Check out namespaces:
http://www.php.net/manual/en/language.namespaces.rationale.php
Wrapping them in a useless class is a workaround implementation of the concept of a namespace. This concept allows you to avoid collisions with other functions in large projects or plugin/module type deployments.
EDIT
Stuck with PHP 5.2?
There's nothing wrong with using a separate file(s) to organize utility functions. Just be sure to document them with comments so you don't end up with bunchafunctions.php, a 20,000 file of procedural code of dubious purpose.
There's also nothing wrong with prefixes. Using prefixes is another way to organize like-purpose functions, but be sure to avoid these "pseudo-namespaces" already reserved by the language. Specifically, "__" is reserved as a prefix by PHP [reference]. To be extra careful, you can also wrap your function declarations in function_exists checks, if you're concerned about conflicting functions from other libraries:
if (!function_exists('myFunction')) {
function myFunction() {
//code
}
}
You can also re-consider your object structure, maybe these utility functions would be more appropriate as methods in a base class that all the other objects can extend. Take a look at inheritance: http://www.php.net/manual/en/language.oop5.inheritance.php. The base class pattern is a common and very useful one:
abstract class baseObject {
protected function doSomething () {
print 'foo bar';
}
public function getSomething () {
return 'bar foo';
}
}
class foo extends baseObject {
public function bar () {
$this->doSomething();
}
}
$myObject = new foo();
$myObject->bar();
echo $myObject->getSomething();
You can experiment with the above code here: http://codepad.org/neRtgkcQ
I would usually stick them in a class anyway and mark the methods static. You might call it a static class, even though PHP actually has no such thing (you can't put the static keyword in front of a class). It's still better than having the functions globally because you avoid possible naming conflicts. The class becomes a sort of namespace, but PHP also has its own namespace which may be better suited to your purpose.
You might even find later that there are indeed properties you can add, even if they too are static, such as lazy-loaded helper objects, cached information, etc.
I'd use classes with static methods in such case:
class Tools {
static public function myMethod() {
return 1*1;
}
}
echo Tools::myMethod();
EDIT
As already mentioned by Chris and yes123: if the hoster already runs PHP 5.3+, you should consider using namespace. I'd recommend a read of Matthew Weier O'Phinney's article Why PHP Namespaces Matter, if you're not sure if it's worth switching to namespaces.
EDIT
Even though the ones generalizing usage of static methods as "bad practice" or "nonsense" did not explain why they consider it to be as such - which imo would've been more constructive - they still made me rethinking and rereading.
The typical arguments will be, that static methods can create dependencies and because of that can make unit testing and class renaming impossible.
If unit testing isn't used at all (maybe programming for home/personal use, or low-budget projects, where no one is willing to pay the extra costs of unit testing implementations) this argument becomes obsolete, of course.
Even if unit testing is used, creation of static methods dependencies can be avoided by using $var::myMethod(). So you still could use mocks and rename the class...
Nevertheless I came to the conclusion that my answer is way too generalized.
I think I better should've wrote: It depends.
As this most likely would result in an open ended debate of pros and cons of all the different solutions technically possible, and of dozens of possible scenarios and environments, I'm not willing going into this.
I upvoted Chris' answer now. It already covers most technical possibilities and should serve you well.
Treating them as a class does give you the benefit of a namespace, though you could achieve the same thing by prefixing them like PHP does with the array_* functions. Since you don't have any properties, that basically implies that all your methods are static (as Class::method()). This isn't an uncommon practice in Java.
By using a class, you also have the ability, if necessary, to inherit from a parent class or interface. An example of this might be class constants defined for error codes your functions might return.
EDIT: If PHP 5.3+ is available, the Namespace feature is ideal. However, PHP versions still lag in a lot of hosts and servers, especially those running enterprise-stable Linux distributions.
I've seen it a few different ways, all have their warts but all worked for the particular project in which they were utilized.
one file with all of the functions
one file with each function as its own class
one massive utilities class with all of the methods
one utils.php file that includes files in utils folder with each
function in its own file
Yes, it's OK formally... As any class is methods + properties. But when you pack in class just some functions -- it`s become not ideal OOP. If you have bunch of functions, that groupped, but not used some class variables -- it' seems, that you have somewhere a design problem.
My current feeling here is "Huston, we have a problem".
If you use exactly functions, there one reason to wrap them in static class - autoloader.
Of course, it creates high coupling, and it's may to be bad for testing (not always), but... Simple functions are not better than static class in this case :) Same high coupling, etc.
In ideal OOP architecture, all functions will be methods of some objects. It's just utopia, but we should to build architecture as close as we can to ideal.
Writing a bunch of "generic-but-related" functions is usually bad idea. Most likely you don't see problem clear enough to create proper objects.
It is bad idea not because it is "not ideal OOP". It is not OOP at all.
"The base class pattern" brought by Chris is another bad idea - google for: "favor composition over inheritance".
"beeing extra careful" with function_exists('myFunction') is not but idea. It is a nightmare.
This kind of code is currently avoided even in modern javascript...

Categories