企业🤖AI智能体构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
### **A Contract Example** ### Interfaces are contracts. Interfaces do not contain any code, but simply define a set of methods that an object must implement. If an object implements an interface, we are guranteed that every method defined by the interface is valid and callable on that object. Since the contract gurantees the implementation of certain methods, type safety becomes more flexible via *polymorphism*. > ### **Polywhat?** ### > > Polymorphism is a big word that essentially means an entity can have multiple forms. In the context of this book, we mean that an interface can have multiple implementations. For example, a ``UserRepositoryInterface`` could have a MySQL and a Redis implementation, and both implementations would qualify as a ``UserRepositoryInterface`` instance. > To illustrate the flexibility that interfaces introduce into strongly typed languages, let's write some simple code that books hotel rooms. Consider the following interface: ~~~ <!-- lang:php --> interface ProviderInterface{ public function getLowestPrice($location); public function book($location); } ~~~ When our user books a room, we'll want to log that in our system, so let's add a few methods to our ``User`` class: ~~~ <!-- lang:php --> class User{ public function bookLocation(ProviderInterface $provider, $location) { $amountCharged = $provider->book($location); $this->logBookedLocation($location, $amountCharged); } } ~~~ Since we are type hinting the ``ProviderInterface``, our ``User`` can safely assume that the ``book`` method will be available. This gives us the flexibility to re-use our ``bookLocation`` method regardless of the hotel provider the user prefers. Finally, let's write some code that harnesses this flexibility: ~~~ <!-- lang:php --> $location = 'Hilton, Dallas'; $cheapestProvider = $this->findCheapest($location, array( new PricelineProvider, new OrbitzProvider, )); $user->bookLocation($cheapestProvider, $location); ~~~ Wonderful! No matter what provider is the cheapest, we are able to simply pass it along to our ``User`` instance for booking. Since our ``User`` is simply asking for an object instances that abides by the ``ProviderInterface`` contract, our code will continue to work even if we add new provider implementations. > ### **Forget The Details** ### > > Remember, interfaces don't actually do anything, They simply define a set of methods that an implementing class must have. >