PHP Classes and Objects Creating Methods Dynamically - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript PHP Classes and Objects Creating Methods Dynamically - Supercoders | Web Development and Design | Tutorial for Java, PHP, HTML, Javascript

Breaking

Post Top Ad

Post Top Ad

Sunday, May 26, 2019

PHP Classes and Objects Creating Methods Dynamically

PHP Classes and Objects



Creating Methods Dynamically

Problem

You want to dynamically provide methods without explicitly defining them.

Use the __call() and __callStatic() magic methods to intercept method invocations and route them accordingly.

This technique is best used when you’re providing an object relational map (ORM) or creating a proxy class. For instance, you want to expose findBy() methods that translate to database queries or RESTful APIs.

For example, you have users of your application and want to let people retrieve them using a varied set search terms: ID, email address, telephone number. You could create one method per term: findById(), findByEmail(), findByPhone(). However, the underlying code is largely identical, so you can put that in one place.

Here’s where __callStatic() comes in:

          class Users {
                 static function find($args) {
                        // here's where the real logic lives
                        // for example a database query:
                        // SELECT user FROM users WHERE $args['field'] = $args['value']
                 }

                 static function __callStatic($method, $args) {
                        if (preg_match('/^findBy(.+)$/', $method, $matches)) {
                               return static::find(array('field' => $matches[1],
                                                                     'value' => $args[0]));
                        }
                 }
          }

          $user = User::findById(123);
          $user = User::findByEmail('rasmus@php.net');

When you invoke findById(), PHP passes this request to __callStatic(). Inside, the regular expression looks for any requests beginning with findBy and extracts the remaining characters. That value and the first argument to the function are then bundled up and passed to Users::find(), where the “real” logic lives.


No comments:

Post a Comment

Post Top Ad