How and when should we use Interface to document systems in PHP?

Asked

Viewed 1,408 times

14

I always wondered exactly, if it is a good practice, to make a system always making use of Interfaces, or this is not necessary?

Interface People {
  public function getName();
  public function setName($string);
  public function getAge();
  public function setAge($string);
}

class User implements People {

  private $name;
  private $age;

  public function __construct()
  {
   return $this; 
  }

  public function setName($string)
  {
     $this->name = $string;
     return $this;
  }

  public function getName()
  {
    return $this->name;
  }

  public function setAge($number)
  {
    $this->age = $number;
    return $this;
  }

  public function getAge()
  {
    return $this->age;
  }

}
  • Ivan, the main advantage I see is that the guy doesn’t have to stare at the code of the class that does something, but simply knows the interface that the class implements

  • So, you see this as an advantage, a colleague of mine from the job said that I should always use it in my systems, but then I get in a glaring doubt, if we start creating a more bureaucratic code, it doesn’t get a very plastered thing?

2 answers

13


Necessary is not, but it is good for several reasons, documenting really is one of them, give more robustness in the code is another.

I just don’t quite understand how dynamic typing languages invest so much in this, it seems to go against their own philosophy of letting the programmer’s tests or intuition detect errors. Even worse when the language is weak.

The interface is a contract which should be followed when making an implementation. Data typing is also a contract. I don’t know why they ignore one form and follow another. Perhaps the languages themselves are gradually admitting that they used a wrong typing philosophy, at least for the most important purposes.

There are languages of script and languages Nterprise, among others, PHP was a language of script who now wants to be a language Nterprise, but the legacy does not allow to make this transition.

Then on a higher level one should ask: why will you use a protective measure in a language that leaves aside other more important protective measures? Few ask this question, and many who do it seriously and can answer it, will decide to change their language.

Of course some protective measure is better than nothing, it is advantageous in itself, not only for this.

It also generalizes (abstract) what it is intended to do, and that’s good. This is an even better reason to use interface. I won’t explain in detail here because already there’s an answer on that.

In short, when we have the interface implemented we can use it to indicate that only what is present in it is what we need. And that any class that implements it can be used concretely to satisfy a specific algorithm. This makes it easy to maintain and configure the application. You don’t stick to the concrete implementation. The advantages are described in the question linked above.

Other languages of script more coherent prefer the Duck Typing.

See more in What is typing style?.

  • One thing I think I should have in PHP is option typing, and multiple method signatures. I just don’t understand the PHP aversion of people working with typed language... rsrs

  • 1

    It’s moving towards having. Dynamic languages are slowly making this transition. Some are faster than others. But they realized that they were in a niche that has less and less importance. Dynamic languages are scripts. The problem is that they started to be used to make applications. Now they realize they need language resources Nterprise. They can no longer avail themselves of the same facilities that were great for scripts.

  • 3

    @Kaduamaral the problem is that anyone who wants a real robust language will no longer want PHP. As it gained a lot of audience, PHP attracted more people, and the language began to earn a lot of things "borrowed" from others. And you’re getting the hassle of using it, too. Today there are people doing a huge class or a whole MVC project to do what you would need in 2 or 3 lines using the native functions procedurally. Loses performance and readability, to do what he learned from "good practices" (the academic ideal), but forgets that he is using PHP.

  • 3

    That is, PHP is great to do what it originally intended. Then it became a matter of marketing to have other things to "not be left behind", which misread the language. No problem using interfaces, OOP, Pattern design complex, the problem is wanting to do this in PHP. Throw away what the language offers best.

  • 4

    @bigown by the way, I think if PHP was bureaucratic, it would never have "pasted". The ease of use and speed with which you do certain things in PHP is what won the market. Now, there are people who keep killing themselves to "structure the application", while there are people just sitting and writing code to solve the real problem, and it works well. Not that I think it’s bad on its own, if you’re going to make a mega-framework to distribute around the world. The hard part is the guy doing half a dozen different applications and worrying about something that will only penalize the end result.

  • @Bacco, do you think frameworks like Symfony For example, is it one of these bureaucracies? Or are you talking specifically about excessive frills when it comes to proposing a structure (I think this can happen with any language)?

  • 2

    @Wallacemaxters if you’re going to use a framework, it’s important that it’s in order (whether OOP or not, whether MVC or not, that’s irrelevant), because it’s an application that conceptually needs to be consistent. It will be the basis of many other things. Unlike an application or website for specific use, or even something that will become naturally obsolete, where it pays to get to the point. Faster, more efficient and easier to arrange when you discover in the middle of the project those things you couldn’t predict. But if you’re going to use framework, work the way it says to work.

  • 1

    Perfect @Bacco, that’s exactly it. The people who argue that PHP is a weak language and etc, do not understand that it is not designed to make business systems and therefore do not need to worry about certain "paradigms" of development. He was just a website access counter and evolved into a programming language. But anyway, I am currently creating my own PHP framework and I am "bureaucratizing" the language, but I believe that this will help me in future projects where I will already have the structure ready and only worry about the project itself.

  • The subject is interesting, they want to create a room to continue?

  • @Kaduamaral, in my view this will help a lot in your learning. You can pass the github from your framework, so I can get some ideas? I’m also making a ;)

  • @Wallacemaxters follow the link: https://github.com/KaduAmaral/Base

  • @Kaduamaral, I stopped by, but maybe one day I’ll come back (when I have time to spend with him, kkkkk) https://github.com/wallacemaxters/Wmframework/tree/master/src/Wmframework

  • 1

    I already think frameworks are great in other languages. In PHP they sound weird. PHP is a language of script!!!! Or it was. Or it still has traces to be. If you like PHP and want the news of it, then use Hack, at least go the right way for good. If you are going to use PHP, use the original.

Show 8 more comments

6

The main advantage I see of this in PHP is the question of providing flexibility to the programmer in the case of using a library where he implements his own resource.

In this case, the programmer could simply use his own class, provided that he implements the interface required to perform such an operation.

An example: These days, I was having trouble with the Facebook library, because I use the Laravel, and the Laravel does not use the native PHP session. Facebook uses the native PHP session. The result is that it was having trouble.

The class of Facebook implements an interface called PersistentDataInterface. This interface had the methods set and get, needed to determine how the data would be saved in the session.

How data typing is done through PersistentDataInterface, I implemented it, causing the methods to save and obtain data directly from the Laravel.

So everything worked out correctly.

So here’s an example:

interface PersistentData {
    public function set($key, $value);
    public function get($key);
}

class Library{
      public function __construct(PersistentData $persist)
      {
            $this->persist = $persist;
      } 
}

class ClasseQueNaoAtendeMeuSistema implements PersistentData
{
     public function set($key, $value) { ... }
     public function get($key);
}

In this case, the construtor class Library requires typing to be the implementation of interface, and not of classe in itself. Therefore, this gives greater flexibility for me to create another class with the interface methods, but that make the data persistence differently!

I believe that using the interface is a good practice when you want to offer more ways your library can interact with other classes. As you "force" the third class to use the methods through the interface, you can call an object method passed by parameter without "being afraid" that the method does not exist and have to keep making thousands of ifs with method_exists.

THE FUTURE

In the PHP7 it will be wonderful to join the resource of the interfaces with the classes anônimas, as this gives even more flexibility. See for example, in the above case, what could be done.

$tempPersist = new class(Database::connection()) implements PersistentData
{
    public function __construct(Database $database)
    {
         $this->database = $database;
    }
    public function set($key, $value)
    {
       $this->database->table('session')->save([$key=>$value]);
    }  

    public function get($key)
    {
         return $this->database->table('session')->get($key);
    }
   
}


 $lib = new Library($tempPersist);
  • 3

    More flexibility than already exists? The.o

  • 3

    It’s more like "more bureaucratization yet"!

  • @Ivanferrer, it would be more bureaucratic if the Facebook library, in my case, only used the PHP session. then I would have to shit on my code for what I needed to work in the right way. Programming also has its bureaucratic parts. Object orientation looks like this: pay now and benefit later. Already the structured gambiarras is : benefit now (the speed) and pay later (with headaches in the changes)

  • @rray, the flexibility I say is not the language itself, but the library itself. There are libraries that to work you have to change the source code (those I do not even install). I speak flexibility in the sense of not be plastered

  • What you mean is that in PHP7, it simplifies polymorphism a little more. It is not in the future, it already exists... Companies that are late...

  • For libraries there is no solution only change anyway. If I understood directly, with the anonymous classes it is possible to 'hack' in line and fix the problem you said, today (php5) the only way would be to create a new class that inherits the problematic (class).

  • 2

    @Ivanferrer are not companies that are late but programmers, see the amount of questions on sopt about using obsolete functions(mysql_*, ereg etc).

  • Some of them are too. That’s why my salary doesn’t go up. No one values us because of these plagues.

  • 2

    @Ivanferrer, let’s not call them "pests". Everyone has already been out on their knees one day, including me. The problem of not knowing and doing a program, is recognizing that it was bad and not fixing. That’s what breaks the bike. I’ve seen people here at SOPT using a handmade database connection, and I was using the Laravel, that has an optimal abstraction model. The problem of making mistakes is not correcting

  • Insecticide corrects. Do gambiarra, is one thing, call the nephew is another.

Show 5 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.