Do interfaces just DESCRIBE what implemenations need to do? - php

I'm just learning about PHP's interfaces as I have never really used them before, but as I understand it they are only a interface, as they are called, to kind of uphold how classes that implement them are structured?
So for example, if you wanted to make two different classes for two different databases you could do:
class mysql {
public function connect() {
// code here
}
public function getData() {
// code here
}
}
class mongoDB {
public function connect() {
// code here
}
public function getData() {
// code here
}
}
...and that would technically be the same as:
interface database {
public function connect() {
}
public function getData() {
}
}
class mysql implements database {
public function connect() {
// code here
}
public function getData() {
// code here
}
}
class mongoDB implements database {
public function connect() {
// code here
}
public function getData() {
// code here
}
}
...am I right? It's just that using an interface it makes sure you don't go doing something like the below and hence not being able to change databases easily?
class mysql {
public function connect_mysql() {
// code here
}
public function getData() {
// code here
}
}
class mongoDB {
public function connect_mongo() {
// code here
}
public function getData() {
// code here
}
}
Is that pretty much the reasoning behind them?

What the interface does is it standardises what your code can rely on, and at the same time decouples that from a specific implementation. Wow, that sounds complicated. It's easier to illustrate it from the perspective of a user of interfaces:
function (MyDatabaseInterface $db) {
$db->connect();
$db->getData();
}
Type hints are a big part of using interfaces. This function declares that its argument must be an instance of MyDatabaseInterface, in other words, any object that implements MyDatabaseInterface. It is entirely up to you what specific object that is, as long as it implements MyDatabaseInterface. And since in MyDatabaseInterface you have specified the methods connect() and getData(), you can be sure that any object being passed in has these methods and that you can call them.
The other way around, have a look at this function:
/**
* #return MyDatabaseInterface
*/
function foo() {
...
}
It is irrelevant what this function does internally, but it declares that it will return an object of type MyDatabaseInterface, in other words some object that implements MyDatabaseInterface. When you call it, you know what you can rely on:
$bar = foo();
$bar->connect();
$bar->getData();
This function may return an instance of mysql or of mongoDB, it is none of your concern. You simply stick to what was declared in the interface and your code will work regardless of what specific object you get.
An interface literally defines the interface between code. It defines what methods code can safely call on other code, without tying down the specifics to specific classes. Your specific objects could define a ton more methods than are defined in the interface; an interface does not declare a class structure. A class could implement several interfaces at once, meaning it implements all the methods of all the interfaces; each individual interface would then just represent a subset of all the possible methods that could be called on an object.
You should describe specific "tasks" or "abilities" which can be accomplished in an interface, not "classes". It's a good sign if your interface names end with "-able", like Iterable. A class can then implement several interfaces and thereby describe all the things it "can do". You can then require function arguments with a certain "ability" at specific points, as shown in the example code above. This isolates and decouples parts of code from one another, which makes your code more flexible, reusable and adaptable to change.
For a useful real world scenario, imagine a larger development team which is working on a large project. There are several sub-teams, each responsible for a different part of the application. They all sit down together and come up with a general plan. At some point, the code of these separate teams needs to interact with each other. They can define these interfaces upfront:
"I'll need to call some method on your code that gives me the user credentials."
"OK, then you'll need to give me some object from which I can get the foobar."
"Then over here we'll have to talk to Joe's component to send the baz data."
...
They can define the different methods they will need to talk to each other in an interface before any code has been written, then go off and do their own thing. They can rely on code which hasn't even been written yet, because they already decided on what the interface will look like. They can even substitute the real code with mock objects for the time being while Joe is still hammering out his real code, then simply switch it in later with whatever Joe comes up with. And all those techniques are useful even if you're just working by yourself.

Related

optional dependencies within a class

I'm looking for some direction regarding the following, I'm new to OOP and getting there but think either my lack of understanding is causing me to get stuck in a rabbit hole or I'm just over thinking things too much and being anal.
basically i have a main class called "CurlRequest" which sole purpose is to perform curl requests, providing a url and params it returns me some html. This class works and functions as intended and I'm happy with that.
I use this class for a few projects but for one I then wanted to track the performance of my requests made. attempted, failed, passed etc, so i created a static class for this which manages all my counters. I place counter references like the following at different areas in my CurlRequest class.
PerformanceTracker::Increment('CurlRequest.Attempted');
PerformanceTracker::Increment('CurlRequest.Passed');
PerformanceTracker::Increment('CurlRequest.Failed');
I have around 10 or so of these with my class tracking all kinds of things during the curl request and i also use my PerformanceTracker class in other classes i made.
However like mentioned i only wanted to do this for one of my projects, so find my self in the situation of having my original CurlRequest class and an altered one with performance counters in it.
My question is, is their a way i can use the same class for any project and choose to use the PerformanceTracker class or not. The obvious way i thought of was to pass an $option argument into the class and then have if statements around all the counters, but can't help think its messy.
if ($this->options['perfCounter'] == true ) {
PerformanceTracker::Increment($this->owner . '.CurlRequest.Failed');
}
this also adds a lot of extra code to the class.
I suggest placing the if statement in a separate method
private function handlePerformanceTracker($q)
{
if ($this->options['perfCounter'] == true ) {
PerformanceTracker::Increment($q);
}
}
And call this method instead of your calls to
PerformanceTracker::Increment(...);
Also if you find that you want to track performance differently between your projects it might be useful to change your constructor to accept a callable argument, this way you externalize the actual implementation from the CurlRequest class itself.
public function __construct(..., callable performanceHandler)
Then when you instantiate your class:
$curlRequest = new CurlRequest(..., function($outcome) {
//your implementation
});
You can use inheritance and create a subclass that performs the logging before delegating to the parents methods:
class PerformanceTracker
{
static function Increment($s)
{
echo $s;
}
}
class CurlRequest
{
function get($url){
//preform curl request, save html to variable etc
//dummy vars used here so working example code
$html = 'html here';
$curlError = false;
if($curlError){
$this->error($curlError);
}
return $this->success($html);
}
protected function success($html)
{
return $html;
}
protected function error($curlError)
{
throw new Exception($curlError);
}
}
class LoggingCurlRequest extends CurlRequest
{
function get($url)
{
PerformanceTracker::Increment('CurlRequest.Attempted');
return parent::get($url);
}
function success($html)
{
PerformanceTracker::Increment('CurlRequest.Passed');
return parent::success($html);
}
function error($curlError)
{
PerformanceTracker::Increment('CurlRequest.Failed');
parent::error($curlError);
}
}
$lcr = new LoggingCurlRequest();
$lcr->get('unused in example');
As i have used dummy classes with minimal code to demo the technique the benefit might not be obvious, but in you real code, the methods in the CurlRequest class will be more complex, but the methods in the logging class will remain as two liners, with the log function and the call to the parent method.
Using this technique you can modify the parent class without effecting the derived classes (provided the method signatures dont change), can create other derived classes (how about a CachingCurlRequest) etc.
For the full benefits of OOP you should look into dependency injection and interfaces
From an OOP perspective you could use the 'Null' object pattern. This just means that the dependency used by the CurlRequest class is abstract (possibly an interface?). You would then have Two concrete implementations of PerformanceTracker: the one you have today and one that does nothing (it does not have any behavior). In this way for the one project when you instantiate the CurlRequest class it would use the concrete implementation that has behavior and for all the other projects it would use the concrete implementation with no behavior. All of the code in CurlRequest would look the same but it would have different behavior depending on which concrete implementation it was using

Is this good practice for encapsulation in PHP?

For instance i have class say that runs MySQL query and i want to encapsulate this class.
class SqlQuery {
private $database_connection_obj;
public function __construct($dbh) {
$this->$database_connection_obj = $dbh;
}
public function runQuery($query, $params) {
//run query implementation...
}
}
Encapsulation and information hiding means that i want to close direct access to class methods so function runQuery() should not be public so i make it private and add method exacuteQuery() with sole purpose to pass data to private function runQuery().
What is the practical use of doing so, because at the end it works exact same as code above.
Should there be some sanitation of input data done in public method before its passed to private method or why write this extra code at all?
class SqlQuery {
private $database_connection_obj;
public function __construct($dbh) {
$this->$database_connection_obj = $dbh;
}
public function exacuteQuery($external_query, $external_params) {
$this->runQuery($external_query, $external_params);
}
private function runQuery($query, $params) {
//run query implementation...
}
}
The main idea is to make classes look like black boxes, meaning that an outsider (namely, another class or function holding an instance of the class) has no idea how it works internally. It's abstract to them.
The internal workings of the query are of no importance to the class holding the query and calling ->run(), it only cares about the query running, not necessarily how or where it runs.
Note that a query specifically is quite the low level abstraction, it's relatively close to making direct calls to standard library functions/objects. But given that low level abstraction, you can make higher level abstraction.
For example, a UserStore, that internally uses SqlQuery objects to get and set User objects into the database. A class using UserStore isn't aware that UserStore is using SqlQuery objects internally, it just knows that it's an object that can save and retrieve User objects.
This sort of "hiding away" and "encapsulating" actually gives you a lot of power, because now classes can use other classes without depending on specific implementation details. If tomorrow you'd like to change the way you store Users, you just make a change to the UserStore class, as long as it has the same public API, the rest of your application wouldn't even be aware that something changed.
Given details has no difference, but it depends upon work. I use it much times when i have to make a function which cannot be access directly but only by the method for its use. It optimize the code and deny access outside the code. Otherwise any one can alter the parameters which can be harmful.

Implementing an interface with different types

I would like to have an interface that allows for a generic type
public function persist($object);
But my concrete implementations to have a type
public function persist(User $user);
From what I understand of PHP this is not possible. From an object oriented design point of view could someone explain to me why what I am doing is misguided and wrong.
Edit: I should clarify, I'm aware of type hinting and how it works my question is really trying to understand from an OO perspective where I am going wrong when I want my concrete implementation to take a different type to the interface.
The interface's purpose is to be a contract between classes. An interface would be useless if multiple concrete classes implemented it, but all expected different inputs. By looking at the interface, you would not know what type of inputs that the implementing classes expect, thus making the interface basically useless. You could not interchange different concrete classes that all use the same interface, as they all expect different inputs (have different interfaces).
I could not replace classA with classB with the assurance that they would both work, since they both have the same interface. This would basically make interfaces useless for every OOP pattern known to man.
EDIT EXAMPLE
class CommandList {
public function addCommand(Command $command) {
$this->commands[] = $command;
}
public function runCommands() {
foreach ($this->commands as $command) $command->run($this);
}
}
interface Command {
public function run(CommandList $commandList);
}
class Hop implements Command {
public function run(CommandList $commandList) {
// hop here
}
}
class Skip implements Command {
public function run(CommandList $commandList) {
// skip here
}
}
See how the interface acts as a contract? If you break that contact, then things that implement Command would not be interchangeable.

PHP: how to reuse code (oop)?

I have studied in php oop and stocked in the concept of reusable code.
I have seen an example like
interface iTemplate
{
public function setVariable($name, $var);
public function getHtml($template);
}
And implement it:
// Implement the interface
class Template implements iTemplate
{
private $vars = array();
public function setVariable($name, $var)
{
$this->vars[$name] = $var;
}
public function getHtml($template)
{
foreach($this->vars as $name => $value) {
$template = str_replace('{' . $name . '}', $value, $template);
}
return $template;
}
}
I can understand the code but not sure why it is reusable. Every time I want to add a new function in iTemplate interface, my Template class needs to be changed too. I don't understand the concept of "reuse". I appreciate any help. Thanks.
Interfaces aren't directly for code reuse. They are for abstraction. They enable classes that use the template to check for the interface instead of the base template class. That way it separates implementation from the interface declaration.
So if your method does something with a template class, checking for an object of instance template would hard code a dependency on that class. But in reality you don't care what class you get, you just care if it adheres to the iTemplate interface (since that's all you're calling anyway).
public function foo(Template $template) {
vs:
public function foo(iTemplate $template) {
Now, as far as code re-use, interfaces aren't really designed for that. Inheritance typically is. Basically think of inheritance as extending an abstraction. Let me give you an example:
If you were to create a set of classes for birds, you could approach it with inheritance and without it. Let's see how we might do it without:
interface iBird {
public function fly();
public function speak();
public function swim();
public function walk();
}
class Duck implements iBird {
public function fly() {
//Fly here
}
public function speak() {
// Quack here
}
public function swim() {
//Swim here
}
public function walk() {
//Walk here
}
}
class Turkey implements iBird {
public function fly() {
//Fly here, but limited
}
public function speak() {
//Make turkey sound here
}
public function swim() {
throw new Exception('Turkeys can not swim!');
}
public function walk() {
//Walk here
}
}
Now, this is a simple example, but you can see that in those two birds, the walk() functions will likely be identical (and hence violate DRY)...
Let's see how that might look with a single tier inheritance:
abstract class Bird implements iBird {
public function fly() {
//Fly here
}
abstract public function speak();
public function swim() {
//Swim here
}
public function walk() {
//Walk here
}
}
class Duck extends Bird {
public function speak() {
//Quack here
}
}
class Turkey extends Bird {
public function speak() {
//Make turkey sound here
}
public function swim() {
throw new Exception('Turkeys can not swim!');
}
}
Now, you can see we just re-used 3 of the methods! We didn't declare speak(), since it will be always overriden (since no two birds sound alike).
Sounds good right? Well, depending on our needs, we may want to add other abstract types. So lets say we were making a lot of different types of birds... We would have some that didn't swim, so we might create an abstract class NonSwimmingBird that extends Bird, but throws the exception for us. Or a NonFlyingBird, or a ShortRangeBird...
Now, we're really on the track as far as code re-use, but we're hitting a wall in another area. Suppose we have a bird that doesn't fly or swim. What class do we inherit from? Either way, we're duplicating code. So we need to find another way out. Well, how do we do it? Through Design Patterns... Instead of direct inheritance, we could use a decorator pattern to add those traits on the fly. (There are other patterns that can be used here, the point is to show that inheritance alone won't suit all needs. And Patterns alone won't either. You need a good architecture using both worlds based upon what your exact needs are)...
The point is, it all depends on your needs. If you only have 2 "classes" of objects you're going to architect something much simpler than if you are planning on having thousands. The point of what I wrote here is to demonstrate how you can use straight inheritance to enforce some DRY principals (but also how straight inheritance can cause code duplication as well). The big thing, is don't try to stick to DRY just because you don't want to repeat yourself. Stick to DRY, but make sure that you're combining and extending where it's reasonable to, otherwise you're creating yourself a maintenance headache. Stick to the Single Responsibility Principal, and you should be fine...
Interface writes only 1 time in beginning of development. And only after this writes other classes implements of this Interface. Interface - is a fundament.
Note: method setVariable isn't required. There are good magic methods in PHP as __get(), and __set().
Interfaces are usually useful in cases where you want something to be interchangeable. Imagine you'd build a Plugin aware application. You then have the interface iPlugin:
interface iPlugin {
public function init();
/* .. */
}
and all Plugins would implement that interface. A plugin manager could then easily check if a Plugin implements the interface and call the init() method on it.
Code doesn't need to be OO to be reusable, although in many cases that helps.
Code certainly doesn't need to use interfaces to be reusable, although again in some cases that will help.
The key to writing reusable code is to write code that is clearly written, well-commented, uses consistent naming and calling conventions, and is more general than it strictly needs to be for the problem at hand.
One of the simplest and most powerful techniques for writing reusable code in PHP is writing methods that accept either a variable number of arguments, or accept an associative array of parameters.
Often, code that didn't start out "intending" to be reusable turns out to be something you'll want to reuse. Typically, code starts "inline" and then you discover you need to do exactly, or nearly exactly, the same thing in more than one place. When you find yourself copying and pasting code it's time to refactor it as a function.
Similarly, when you find yourself wishing a function you had defined in file X would be really helpful in file Y, it's time to move it into a module.
The best way to learn all this is by experience. Some people will tell you to architect this stuff from the beginning, and that's certainly a good idea if you have the insight and experience to do so, but it's just as valid to do so from the bottom up, and it's probably the best way to learn.
Reusability of Object oriented Programming is the use of previous class or function or method in the present class but no problem of previous class.

php OOP function declarations

I'm a big fan of OOP in php, but i feel like defining class methods gets disorganized so fast. I have a pretty good background in OOP in C++, and i am pretty comfortable with how it is handled there, and am curious if there are ways to do it similarly in php.
To be more specific, here is what i mean. I like how in C++ you can define a class header (myclass.h) and then define the actual details of the functions in the implementation file (myclass.cc). Ive found that this can easily be replicated using interfaces in php, but i havent found a good solution for the following:
I like to organize my code in C++ in different files based on how they are accessed, so for example, public methods that can be called outside of the class would be in 1 place, and private methods would be organized somewhere else - this is personal preference.
Ive tried to define class methods in php like:
private function MyPHPClass::myFunction(){ }
when the definition isnt directly inside the class block( { } ), but i havent had any success doing this.
Ive been through all of the pages on php.net, but couldnt find anything like this. Im assuming that there is no support for something like this, but thought i would ask anyway.
thanks
You can't do this. The class declarations are Java-like.
You have to put everything in one file or, at minimum, have some helper classes -- be they only static methods to which you forward or calls or with you deferring some implementation to encapsulated objects. You can also use the __call and __callstatic magic methods to reduce the size of your stubs, but that only works for public methods and I would recommend that you avoid magic methods.
EDI2: As RobertPitt pointed in a comment, you should consider alternative strategies that divide the functionality between several classes. It has the added advantage that it can make your code more decoupled. If you need, you can still unify the functionality of the several classes behind a façade.
EDIT: By using magic methods, I mean something like this:
class MyClassHelper {
public function method_one(array $args) {
...
}
public function method_two(array $args) {
...
}
}
class MyClass {
/**
* #var MyClassHelper
*/
private $helper;
private static $ALLOWED_METHODS = array("method_one" => NULL,
"method_two" => NULL);
public function __call($name, $arguments) {
$name = strtolower($name);
if (array_key_exists($name, self::$ALLOWED_METHODS) {
$helper->$name($arguments);
}
else
throw new Exception(...);
}
}
I should recommend that you avoid this, there are many pitfalls to this (handling of references, no code completion).
Im not really a C++ / C# Programmer but interfaces in php i can give you an exampe to see if this helps.
Interface
interface IDatabase
{
public function connect($dns = '');
public function disconnect($flushCache = false); //Do not use braces, Code free in interfaces
}
Database abstract base class
abstract class Database
{
//Some driver logic here to laod mysql,oracle etc
}
MySql Driver
class DBDriver_MySQl extends Database implements IDatabase
{
public function connect($dns = '')
{
//Connection logic.
}
public function disconnect($flushDns)
{
//Disconnect Login
}
}
Hope this is what your looking for.

Categories