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.
Related
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.
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.
I'm trying to design some class hierarchy and I got "stuck" at this part.
Lets say that I have following classes
abstract class Video
{
const TYPE_MOVIE = 1;
const TYPE_SHOW = 2;
abstract public function getTitle();
abstract public function getType();
}
class Movie extends Video
{
// ...
public function getType()
{
return self::TYPE_MOVIE;
}
}
class Show extends Video
{
// ...
public function getType()
{
return self::TYPE_SHOW;
}
}
In the diffrent part of the system I have (Parser) class that encapsulates creation of
movie and show objects and returns obj. to the client.
Question: What is the best way to get a type of a obj. returned from parser/factory class, so that client can do something like
$video = $parser->getVideo('Dumb and Dumber');
echo $video->getTitle();
// Way 1
if($video->getType == 'show') {
echo $video->getNbOfSeasons();
}
// Way 2
if($video instanceof Show) {
echo $video->getNbOfSeasons();
}
// Current way
if($video->getType == Video::TYPE_SHOW) {
echo $video->getNbOfSeasons();
}
Is there a better way than my solution (read as: does my solution suck?)?
Is there a better way than my solution (read as: does my solution suck?)?
Your solution does not suck, per se. However, whenever someone is trying to determine the subtype to perform some actions, I tend to wonder; why? This answer might be a little theoretical and perhaps even a little pedantic, but here goes.
You shouldn't care. The relationship between a parent and a child class is that the child class overwrites the behaviour of the parent. A parent class should always be substitutable by it's children, regardless which one. If you find yourself asking: how do I determine the subtype, you're usually doing one of two things "wrong":
You're attempting to perform an action based upon subtype. Normally, one would opt for moving that action to the class itself, instead of "outside" of the class. This makes for more manageable code as well.
You're attempting to fix a problem you've introduced yourself by using inheritance, where inheritance isn't warranted. If there is a parent, and there are children, each of which are to be used differently, each of which have different methods, just stop using inheritance. They're not the same type. A film is not the same a tv-serie, not even close. Sure, you can see both on your television, but the resemblance stops there.
If you're running into issue number 2, you're probably using inheritance not because it makes sense, but simply to reduce code duplication. That, in and on itself, is a good thing, but the way you're attempting to do so might not be optimal. If you can, you could use composition instead, although I have my doubts where the duplicated behaviour would be, apart from some arbitrary getters and setters.
That said, if your code works, and you're happy with it: go for it. This answer is correct in how to approach OO, but I don't know anything about the rest of your application, so the answer is generic.
I'd go with way 2. It abstracts you the need to add another constant at Video in case you may want to add class SoapOpera extends Show (for instance).
With way #2, you are less dependent on constants. Whatever information you can gain without hardcoding it, means less problems to likely happen in the future in case you want to extend. Read about Tight an Loose Coupling.
I think the second option is better, using instanceof. This is in general common to all OOP design and not just PHP.
With your first option, you have specifics about derived classes in the base class, and thus must modify the base class for each new derived class you add, which should always be avoided.
Leaving the base class as-is when adding new derived classes promotes code reuse.
If there is a "right" way, and everything is subjective in coding of course (as long as it doesn't adversely impact performance/maintainability ;) ), then it's the second way as "Truth" and "Brady" have pointed out.
The upside of doing things the way you're doing them now (class constants in the abstract) is that when you're working with other developers it can provide hints as to how you expect the abstract class to be interacted with.
For instance:
$oKillerSharkFilm = Video::factory(Video::MOVIE, 'Jaws', 'Dundundundundundun');
$oKillerSharkDocumentary = Video::factory(Video::DOCUMENTARY, 'Jaws', 'A Discovery Shark Week Special');
Of course, the downside is that you have to maintain the "allowable extensions" in the abstract class.
You could still use the instanceof method as demonstrated in your question and maintain the list of allowable extension in the abstract predominantly for control/type fixing.
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...
I am trying to improve my knowledge of OOP in PHP and have been researching abstract classes and interfaces.
What I have learned
They are both classes that cannot be instantiated themselves but can olny be extended (implemented in the case of interfaces)
Abstract classes provide methods and properties for other classes that extend them.
If a class uses an abstract method then the class itself must also be abstract.
If an abstract method is defined within an abstract class, all child classes must define the details of that method. Methods not defined as abstract can be used in the same way as normal methods.
Interfaces define what methods a class that implements it must have. The functionality of the methods are not defined in the interface, the interface just offers a list of methods that must be included in the child class.
An interface does not define any properties.
Classes can implement as many interfaces as they want to but they must define a method for every one of the interfaces they implement
I think that covers the basics. Please feel free to add to that if you think there's anything I have missed.
What I would like to know is if there are any real world examples of implementation of these classes, especially the interface class. Does anyone know of any open source applications that use them that I can browse to better understand them and see where and when they are used effectively? I have come across book examples which use animals which fails to demonstrate the importance of these classes.
The final keyword prevents the class being extended by other classes, example:
class Parent
{
}
class Mother extends Parent
{
}
final class Brother extends Mother /* - This class cannot be extended - */
{
}
class Pet extends Brother
{
}
The Pet class will throw an error stating: Fatal error: Class Pet may not inherit from final class (Brother)
This is also available for methods, so if you do not want to allow the methods to be inherited causing the child class to have the same method acting as an override.
http://php.net/manual/en/language.oop5.final.php
Yo used that you would like some real world examples of what interfaces can be used for, well a database abstraction layer
You have 1 base class which provides the basic methods to iterate your database data, but that would use a sub class for the the database type, such as MySql,MsSql etc, each database type would have its own class, but for the base class to make sure that it has these methods they would all implement the same interface.
Example
interface IDatabaseLayer
{
public function connect();
public function query();
public function sanitize();
//...
}
So the base class knows that MySql and MsSql have the above methods, thus reducing errors and being more organized.
When passing in objects to classes you want to be sure that the Object is of a certain type, PHP5 allows you to define what type of object should be passed into the methods as params.
lets say you have 3 classes
DatabaseCredentials
DatabaseConnection
DatabaseQuery
you can specifically define in the constructuin of DatabaseConnection that you require a DatabaseCredentials class like so:
class DatabaseConnection implements Connectable
{
public function __construct(DatabaseCredentials $ConnectionDetails)
{
$this->Connect($ConnectionDetails->BuildDSN());
}
}
A good way to really get started is by reading here:
http://php.net/manual/en/language.oop5.php
Another feature of PHP5 you may wish to look at is name spaces, this will allow you to keep your code organized, have multiple objects with the same name, makes auto loading more efficiently
Small Example:
namespace Database\MySql
{
class Database{}
}
namespace Database\MsSql
{
class Database{}
}
And you can just use like:
use Database;
$Database = new MySql\Database();
PHP comes with few interfaces predefinded by default: http://www.php.net/manual/en/reserved.interfaces.php
PHP also contains Standard PHP Library (SPL), which defines more:
interfaces http://www.php.net/manual/en/spl.interfaces.php
classes, including abstract ones: http://www.php.net/manual/en/spl.datastructures.php
Zend Framework is also very good example where such concepts are used. http://framework.zend.com/
Not a real world example as such, but one Design Pattern where you usually encounter interfaces and abstract classes is the Command Pattern. See link for example code.
In general, "programming against an interface" is considered good OO practise, because it decouples concrete implementations and let you more easily change them for other implementations, e.g. instead of asking for a specific class
public function fn(ConcreteClass $obj)
{
$obj->doSomething()
}
you just ask that it provides a certain set of methods
public function fn(MyInterface $obj)
{
$obj->doSomething()
}
Interfaces also help teasing apart large inheritance structures. Because PHP supports only Single Inheritance, you'll often see hierarchies like this:
BaseClass -> Logger -> Auth -> User
where each of these contains specific aspects used inside these classes. With an interface, you just do
User implements Loggable, Authenticable
and then include that specific code via Strategy Patterns or Composition/Aggregation, which is ultimately much more maintainable.
For a list of predefined interfaces in PHP see my answer to:
where to find "template" interfaces?.
You may follow the "PHP patterns" series by Giorgio Sironi in dzone or directly in his blog, really interesting if you are interested patterns and OOP.
Also you could take a look to the Best PHP programming book in stackoverflow if you're in need of a good PHP book.
We can say that interface is purely 100% abstract class but abstract is not. Because many time we defines function in abstract class. But in interface class we always declare function.