I am developing a php application using MVC architecture and i really need suggestions about the following design guidelines:
According to php class structure best practises, its noted that someone should minimize module dependencies, my application class inheritance is as followed:
some operations/methods are accessible by all classes
what i have done is i have created an HelperClass which will contain all these "global" methods like string manipulations, integer manipulations, array manipulations and then let the other classes which would like to use these methods extend the class.
Class organization:
interface StringHelper{
...
}
interface ArrayHelper{
...
}
class GeneralHelper implements StringHelper, ArrayHelper{
......
}
class NewClass extends GeneralHelper{
...
}
// user factory style to create object
class NewClassFactory{
public function create( $options ){
return new NewClass( $options );
}
}
The application has about 15 classes.
Is this approach suitable for this scenario or will i end up having big issues when maintaining my application?
Would appreciate for your help.
In most cases helper classes should always be static and no working class should extend it. Helpers are global and they have no role in the main scope of the working class. Think of helpers as Plumbers, Handymen etc . If you are writing a family class it shouldn't extend plumbers, Plumbers should come in when needed and out with no relation whatsoever to the family.
What you need is this:
class NewClass {
...
$some_string = declaration
$some_string = StringHelper::sanitizeString($some_string);
}
Related
So I have a situation in an application where there is a CONSOLE app and WEB app.
Now if one knows Yii2 then he knows. There is
yiisoft/yii2/base/ErrorHandler.php
which is extended by
yiisoft/yii2/web/ErrorHandler.php
( FOR WEB in main.php config )
and
yiisoft/yii2/console/ErrorHandler.php ( FOR CONSOLE in main.php config )
Now here I want to override handleException function from yiisoft/yii2/base/ErrorHandler.php. Both ErrorHandler ( web and console ) do not override this method. This method is only in BaseErrorHandler.
So right now, I am extending both ErrorHandler from WEB and CONSOLE.
So I do have to make same changes in two different files/classes. For it to work.
What if I just want to extend BaseErrorHandler and do changes in new class ( ONLY ONE class ) there and make it available in both classes which extends base class.
You can not have a class extending two classes. You can achieve what you want however through the use of Traits. Traits by definition from the guide here is:
"a mechanism for code reuse in single inheritance languages
such as PHP. A Trait is intended to reduce some limitations of single
inheritance by enabling a developer to reuse sets of methods freely in
several independent classes living in different class hierarchies."
Practically what you need to do is create a trait containing the desired function with the desired behavior. Example:
trait handleExceptionMyWay {
public function handleException($exception) {
//Put here the desired functionality. Example:
return "Hello";
}
}
And then in each of your classes you should add the statement use handleExceptionMyWay; as such
class MyWebErrorHandler extends yii\web\ErrorHandler {
use handleExceptionMyWay;
}
This way the function that is defined in the trait is going to be used and not the original function from base\ErrorHandler
For this question I want to present my current design and my idea of using a trait. I would like to know whether my understanding of traits is correct and whether my problem can be solved with another design not involving them.
My current class hierarchy in my framework looks like this:
interface IPage { /* ... */ }
interface IForm extends IPage { /* ... */ }
abstract class AbstractPage implements IPage { /* ... */ }
abstract class AbstractForm extends AbstractPage implements IForm { /* ... */ }
In my applications that are based on the framework I used to have the following:
abstract class AbstractBasePage extends AbstractPage { /* ... */ }
Thus I could add some more stuff to all pages for this particular application that is not common to the framework or other applications. This worked well until I implemented the separation into pages and forms as indicated in the first snippet. Now I ended up with something like this:
abstract class AbstractBasePage extends AbstractPage { /* ... */ }
abstract class AbstractBaseForm extends AbstractForm { /* ... */ }
Let's assume in one application there should be a variable for each page and form that indicates whether something special is displayed in the templates. I would need to introduce the same variable in AbstractBasePage and in AbstractBaseForm. Doing so would force me to keep both snippets in sync which isn't good at all.
I was thinking about creating a trait that exposes variables and functions to both classes which they can in turn refer to in the corresponding functions. Using such a trait would reduce the code duplication at least since I could introduce one publicly accessible method that gets called by both classes but other than that there is a decent abstraction, isn't it?
Is this what traits are supposed to help with? Is there a more suitable approach?
In this particular case I ended up introducing an interface (with functions used by the framework) as a contract that gets extended by IPage. Furthermore I had the particular implementation that is identical for pages and forms in a trait which then in turn got used in the framework classes AbstractPage and AbstractForm.
The mentioned implementation was inside the framework itself to have a concise design which then in turn is used to do that in my applications as well. For the applications I introduced a trait which holds the variables and functions that are identical in both pages and forms once again which then gets used in the AbstractBasePage and AbstractBaseForm classes.
For this scenario I needed a what is essentially a language assisted copy and paste feature since I wanted to add something that is not as easily to be done using inheritance but something that can be introduced to classes that are part of different class hierarchies. Therefore I decided to use traits.
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
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.
I have a system of Models:
abstract class R00_Model_iUnique { }
abstract class R00_Model_iFamilyUnique extends R00_Model_iUnique { } // for models with hierarchy
abstract class R00_Model_iTaggedUnique extends R00_Model_iUnique { } // for models with tags
// and, for example
class R00_Model_User extends R00_Model_iUnique { }
class R00_Model_Comment extends R00_Model_iFamilyUnique { }
class R00_Model_Post extends R00_Model_iTaggedUnique { }
There is gonna be R00_Model_iCommentableUnique and R00_Model_Post wants to be inherited from it. But It isn't possible, it's already inherited from R00_Model_iTaggedUnique, and I don't think It's clever to inherit R00_Model_iTaggedUnique from R00_Model_iCommentableUnique or vice versa. I've thought up only one idea how to implement it, but I have some doubts. Maybe you can tell me about some smart methods or criticize that method?
I thought up to make R00_Model_i*Unique not classes, but interfaces, and create helper objects, such as R00_Model_Helper_iUnique (maybe it is a common patern, and there is a cool name, I don't think 'Helper' will be cool there?). Then, in R00_Model_iUnique, create __call(), which checks all the Interfaces of a called object and looks up a called method in the helper.
Or there is too many reflection and other evil slow stuff, isn't it?
You are in the right direction with using an interface and helpers (composition).
This is precisely one of the reasons why on of the principles of the Design Patterns Book (GoF) is "Favor composition over inheritance".
Composition will give you the flexibility you require to use methods of different classes
In the class that you need it.