begin process at 2012 05 27 18:05:17
  Trouver un code source :
 
dans
 
Accueil > 

Code

 > 

Class et Objet ( POO )

 > POO - OBJECT CLASS

POO - OBJECT CLASS


 Information sur la source

Note :
Aucune note
Catégorie :Class et Objet ( POO ) Classé sous :Poo, Class, Object, Hierachie Niveau :Débutant Date de création :12/01/2010 Date de mise à jour :13/01/2010 10:44:20 Vu :2 301

Auteur : Waredan

Ecrire un message privé
Commentaire sur cette source (2)
Ajouter un commentaire et/ou une note

 Description

Une classe "racine" permettant d'éviter des erreurs fatales et facilitant le débogue, il suffit de l'étendre pour profiter de ces fonctionnalités.

Source

  • <?php
  • /**
  • * Class Object is the root of the class hierarchy.
  • *
  • * Every class has Object as a superclass and implements following features:
  • * - Adds the ability to reverse-engineer classes, interfaces, functions,
  • * methods and extensions of the object using PHP reflection API;
  • * - Generates an unique identifier of an object that can be used as a hash key
  • * for storing objects or for identifying an object;
  • * - Prints a representation of the object when it is converted to a string;
  • * - Avoids fatal errors (throws LogicException or BadMethodCallException
  • * instead) when:
  • * - writing or reading data from inaccessible properties;
  • * - calling isset(), empty() or unset() on inaccessible properties;
  • * - calling an object as a function;
  • * - calling inaccessible methods in an object or static context.
  • *
  • * @author Quentin Berlemont <quentinberlemont@gmail.com>
  • * @copyright Copyright (C) 2010 Quentin Berlemont
  • * @license http://www.gnu.org/licenses/lgpl.html LGPLv3
  • */
  • abstract class Object
  • {
  • /**
  • * Returns an instance of ReflectionObject.
  • *
  • * The ReflectionObject class is a part of the PHP Reflection API that adds
  • * the ability to reverse-engineer classes, interfaces, functions, methods
  • * and extensions of an object.
  • *
  • * See the {@link http://php.net/reflection Reflection API} feature for more
  • * information.
  • *
  • * @param void
  • * @return ReflectionObject Returns an instance of ReflectionObject.
  • */
  • final public function getReflection()
  • {
  • static $reflection = null;
  • return $reflection ?: $reflection = new ReflectionObject($this);
  • }
  • /**
  • * Returns an unique identifier of the object.
  • *
  • * This identifier is unique for each object and is always the same for the
  • * same object. It can be used as a key for storing objects or for
  • * identifying an object.
  • *
  • * See the {@link http://php.net/spl-object-hash spl_object_hash} feature
  • * for more information.
  • *
  • * @param void
  • * @return string Returns an unique identifier of the object.
  • */
  • final public function getHashCode()
  • {
  • return spl_object_hash($this);
  • }
  • /**
  • * Prints a representation of the object when it is converted to a string.
  • *
  • * The string consisting of the name of the class of which the object is an
  • * instance, the at-sign character `@`, and the unique identifier for the
  • * object.
  • *
  • * @param void
  • * @return string Returns a string representation of the object.
  • */
  • public function __toString()
  • {
  • return $this->getReflection()->getName() . '@' . $this->getHashCode();
  • }
  • /**
  • * Throws an LogicException when writing data to inaccessible properties.
  • *
  • * @param string $propertyName The name of the property being set.
  • * @param mixed $propertyValue The value for the property.
  • * @return void
  • * @throws LogicException If one tries to write data to inaccessible
  • * properties.
  • */
  • public function __set($propertyName, $propertyValue)
  • {
  • $className = $this->getReflection()->getName();
  • throw new LogicException("Write data to inaccessible property `{$className}::{$propertyName}`.");
  • }
  • /**
  • * Throws an LogicException when reading data from inaccessible properties.
  • *
  • * @param string $propertyName The name of the property to retrieve.
  • * @return void
  • * @throws LogicException If one tries to read data from inaccessible
  • * properties.
  • */
  • public function __get($propertyName)
  • {
  • $className = $this->getReflection()->getName();
  • throw new LogicException("Read data from inaccessible property `{$className}::{$propertyName}`.");
  • }
  • /**
  • * Throws an LogicException when calling isset() or empty() on inaccessible
  • * properties.
  • *
  • * @param string $propertyName The name of the property to be checked.
  • * @return void
  • * @throws LogicException If one tries to apply isset() or empty() on
  • * inaccessible property.
  • */
  • public function __isset($propertyName)
  • {
  • $className = $this->getReflection()->getName();
  • throw new LogicException("Apply isset() or empty() on inaccessible property `{$className}::{$propertyName}`.");
  • }
  • /**
  • * Throws an LogicException when calling unset() on inaccessible properties.
  • *
  • * @param string $propertyName The name of the property to be unset.
  • * @return void
  • * @throws LogicException If one tries to apply unset() on inaccessible
  • * property.
  • */
  • public function __unset($propertyName)
  • {
  • $className = $this->getReflection()->getName();
  • throw new LogicException("Apply unset() on inaccessible property `{$className}::{$propertyName}`.");
  • }
  • /**
  • * Avoids a fatal error when calling an object as a function, throwing a
  • * LogicException instead.
  • *
  • * @param void
  • * @return void
  • * @throws LogicException If one tries to call an object as a function.
  • */
  • public function __invoke()
  • {
  • $className = $this->getReflection()->getName();
  • throw new LogicException("Call object `{$className}` as a function.");
  • }
  • /**
  • * Avoids a fatal error when calling inaccessible methods in an object
  • * context, throwing a BadMethodCallException instead.
  • *
  • * @param string $methodName The name of the method being called.
  • * @param array $arguments Optional, an enumerated array containing the
  • * arguments passed to the method.
  • * @return void
  • * @throws BadMethodCallException If one tries to call inaccessible methods
  • * in an object context.
  • */
  • public function __call($methodName, array $arguments = null)
  • {
  • $className = $this->getReflection()->getName();
  • throw new BadMethodCallException("Call to inaccessible method `{$className}::{$methodName}()`.");
  • }
  • /**
  • * Avoids a fatal error when calling inaccessible methods in a static
  • * context, throwing a BadMethodCallException instead.
  • *
  • * @param string $methodName The name of the method being called.
  • * @param array $arguments Optional, an enumerated array containing the
  • * arguments passed to the method.
  • * @return void
  • * @throws BadMethodCallException If one tries to call inaccessible methods
  • * in a static context.
  • */
  • static public function __callStatic($methodName, array $arguments = null)
  • {
  • $className = get_called_class();
  • throw new BadMethodCallException("Call to inaccessible static method `{$className}::{$methodName}()`.");
  • }
  • }
  • // Example
  • class Foo extends Object
  • {
  • const CONST_VALUE = 'A constant value';
  • private $_var = null;
  • public function bar()
  • {
  • echo 'Hello World !';
  • }
  • }
  • try {
  • $foo = new Foo();
  • // pritns: Array ( [CONST_VALUE] => A constant value )
  • // print_r($foo->getReflection()->getConstants());
  • // prints: 0000000050ce9726000000002e61f3e9
  • // echo $foo->getHashCode();
  • // prints: Foo@0000000050ce9726000000002e61f3e9
  • // echo $foo;
  • // prints (LogicException): Write data to inaccessible property `Foo::_var`.
  • // $foo->_var = 'Some value';
  • // prints (LogicException): Call object `Foo` as a function.
  • // $foo('Hello World !');
  • // prints (BadMethodCallException): Call to inaccessible method `Foo::method().
  • // $foo->method();
  • // prints (BadMethodCallException): Call to inaccessible static method
  • // `Foo::method()`.
  • // $foo::method();
  • // prints: Hello World !
  • // $foo->bar();
  • }
  • catch (Exception $exception) {
  • echo $exception->getMessage() . PHP_EOL;
  • }
  • ?>
<?php
/**
 * Class Object is the root of the class hierarchy.
 *
 * Every class has Object as a superclass and implements following features:
 * - Adds the ability to reverse-engineer classes, interfaces, functions,
 *   methods and extensions of the object using PHP reflection API;
 * - Generates an unique identifier of an object that can be used as a hash key
 *   for storing objects or for identifying an object;
 * - Prints a representation of the object when it is converted to a string;
 * - Avoids fatal errors (throws LogicException or BadMethodCallException
 *   instead) when:
 *     - writing or reading data from inaccessible properties;
 *     - calling isset(), empty() or unset() on inaccessible properties;
 *     - calling an object as a function;
 *     - calling inaccessible methods in an object or static context.
 *
 * @author     Quentin Berlemont <quentinberlemont@gmail.com>
 * @copyright  Copyright (C) 2010 Quentin Berlemont
 * @license    http://www.gnu.org/licenses/lgpl.html LGPLv3
 */
abstract class Object
{
    /**
     * Returns an instance of ReflectionObject.
     *
     * The ReflectionObject class is a part of the PHP Reflection API that adds
     * the ability to reverse-engineer classes, interfaces, functions, methods
     * and extensions of an object.
     *
     * See the {@link http://php.net/reflection Reflection API} feature for more
     * information.
     *
     * @param  void
     * @return ReflectionObject Returns an instance of ReflectionObject.
     */
    final public function getReflection()
    {
        static $reflection = null;

        return $reflection ?: $reflection = new ReflectionObject($this);
    }

    /**
     * Returns an unique identifier of the object.
     *
     * This identifier is unique for each object and is always the same for the
     * same object. It can be used as a key for storing objects or for
     * identifying an object.
     *
     * See the {@link http://php.net/spl-object-hash spl_object_hash} feature
     * for more information.
     *
     * @param  void
     * @return string Returns an unique identifier of the object.
     */
    final public function getHashCode()
    {
        return spl_object_hash($this);
    }

    /**
     * Prints a representation of the object when it is converted to a string.
     *
     * The string consisting of the name of the class of which the object is an
     * instance, the at-sign character `@`, and the unique identifier for the
     * object.
     *
     * @param  void
     * @return string Returns a string representation of the object.
     */
    public function __toString()
    {
        return $this->getReflection()->getName() . '@' . $this->getHashCode();
    }

    /**
     * Throws an LogicException when writing data to inaccessible properties.
     *
     * @param  string $propertyName  The name of the property being set.
     * @param  mixed  $propertyValue The value for the property.
     * @return void
     * @throws LogicException If one tries to write data to inaccessible
     *                        properties.
     */
    public function __set($propertyName, $propertyValue)
    {
        $className = $this->getReflection()->getName();

        throw new LogicException("Write data to inaccessible property `{$className}::{$propertyName}`.");
    }

    /**
     * Throws an LogicException when reading data from inaccessible properties.
     *
     * @param  string $propertyName The name of the property to retrieve.
     * @return void
     * @throws LogicException If one tries to read data from inaccessible
     *                        properties.
     */
    public function __get($propertyName)
    {
        $className = $this->getReflection()->getName();

        throw new LogicException("Read data from inaccessible property `{$className}::{$propertyName}`.");
    }

    /**
     * Throws an LogicException when calling isset() or empty() on inaccessible
     * properties.
     *
     * @param  string $propertyName The name of the property to be checked.
     * @return void
     * @throws LogicException If one tries to apply isset() or empty() on
     *                        inaccessible property.
     */
    public function __isset($propertyName)
    {
        $className = $this->getReflection()->getName();

        throw new LogicException("Apply isset() or empty() on inaccessible property `{$className}::{$propertyName}`.");
    }

    /**
     * Throws an LogicException when calling unset() on inaccessible properties.
     *
     * @param  string $propertyName The name of the property to be unset.
     * @return void
     * @throws LogicException If one tries to apply unset() on inaccessible
     *                        property.
     */
    public function __unset($propertyName)
    {
        $className = $this->getReflection()->getName();

        throw new LogicException("Apply unset() on inaccessible property `{$className}::{$propertyName}`.");
    }

    /**
     * Avoids a fatal error when calling an object as a function, throwing a
     * LogicException instead.
     *
     * @param  void
     * @return void
     * @throws LogicException If one tries to call an object as a function.
     */
    public function __invoke()
    {
        $className = $this->getReflection()->getName();

        throw new LogicException("Call object `{$className}` as a function.");
    }

    /**
     * Avoids a fatal error when calling inaccessible methods in an object
     * context, throwing a BadMethodCallException instead.
     *
     * @param  string $methodName The name of the method being called.
     * @param  array  $arguments  Optional, an enumerated array containing the
     *                            arguments  passed to the method.
     * @return void
     * @throws BadMethodCallException If one tries to call inaccessible methods
     *                                in an object context.
     */
    public function __call($methodName, array $arguments = null)
    {
        $className = $this->getReflection()->getName();

        throw new BadMethodCallException("Call to inaccessible method `{$className}::{$methodName}()`.");
    }

    /**
     * Avoids a fatal error when calling inaccessible methods in a static
     * context, throwing a BadMethodCallException instead.
     *
     * @param  string $methodName The name of the method being called.
     * @param  array  $arguments  Optional, an enumerated array containing the
     *                            arguments  passed to the method.
     * @return void
     * @throws BadMethodCallException If one tries to call inaccessible methods
     *                                in a static context.
     */
    static public function __callStatic($methodName, array $arguments = null)
    {
        $className = get_called_class();

        throw new BadMethodCallException("Call to inaccessible static method `{$className}::{$methodName}()`.");
    }
}

// Example 

class Foo extends Object
{
    const CONST_VALUE = 'A constant value';

    private $_var = null;

    public function bar()
    {
        echo 'Hello World !';
    }
}

try {
    $foo = new Foo();

    // pritns: Array ( [CONST_VALUE] => A constant value )
    // print_r($foo->getReflection()->getConstants());

    // prints: 0000000050ce9726000000002e61f3e9
    // echo $foo->getHashCode();

    // prints: Foo@0000000050ce9726000000002e61f3e9
    // echo $foo;

    // prints (LogicException): Write data to inaccessible property `Foo::_var`.
    // $foo->_var = 'Some value';

    // prints (LogicException): Call object `Foo` as a function.
    // $foo('Hello World !');

    // prints (BadMethodCallException): Call to inaccessible method `Foo::method().
    // $foo->method();

    // prints (BadMethodCallException): Call to inaccessible static method
    // `Foo::method()`.
    // $foo::method();

    // prints: Hello World !
    // $foo->bar();
}
catch (Exception $exception) {
    echo $exception->getMessage() . PHP_EOL;
}
?>



 Historique

13 janvier 2010 10:44:20 :
Correction mineures.

 Sources du même auteur

Source avec Zip POO - LOGGING PACKAGE
Source avec Zip POO - FACTORY CLASS
POO - SINGLETON CLASS
POO - PARAMETERHOLDER CLASS

 Sources de la même categorie

Source avec Zip GÉNÉRATION AUTOMATIQUE DE FICHIER .CLASS.PHP EN FONCTION D'U... par ig3
CLASSE D'OBJET DE CRYPTAGE ET DÉCRYPTAGE DE CHAINES DE CARAC... par 8Tnerolf8
Source avec Zip MY.DEVIANTART API par inwebo
CLASSE DE GESTION DE "VARIABLES GLOBALES D'ENVIRONNEMENT" par pifou25
Source avec Zip COLLECTION.CLASS.MIN.PHP par thunderhunter

 Sources en rapport avec celle ci

Source avec Zip Source avec une capture MY.EXCEPTION par inwebo
Source avec Zip POO - LOGGING PACKAGE par Waredan
Source avec Zip POO - FACTORY CLASS par Waredan
POO - SINGLETON CLASS par Waredan
POO - PARAMETERHOLDER CLASS par Waredan

Commentaires et avis

Commentaire de neigedhiver le 12/01/2010 18:20:00

C'est intéressant. En fait, toutes tes classes postées depuis 2 jours sont intéressantes.
J'aurais peut-être stocké le nom de la classe dans une variable statique dans une méthode name(), un peu comme pour getReflection(), mais comme, justement, l'objet réflexion est "mis en cache" de cette manière, ça doit se jouer à quelques millionnièmes de poil de cul en terme de perfs...

Non non, vraiment, ça fait plaisir de voir des sources toutes simples mais très très propres, intéressantes, 100% POO... Ca change... N'est-ce pas Kohntark ?

Commentaire de Waredan le 13/01/2010 15:30:23

Merci pour ton commentaire, toutes ces sources proviennent d'un projet personnel de mini framework MVC, non pas pour réinventer la roue mais pour ma satisfaction personnelle. Sauf qu'étant un clone de Monk, je peux pas continuer si le code ne me semble pas "beau", alors je les poste ici, d'une part, pour en faire profiter la communauté PHP, d'autre part, ça me semble être une bonne idée pour recevoir des critiques et les améliorer.

 Ajouter un commentaire


Discussions en rapport avec ce code source dans le forum

[POO] Une classe dans une classe [ par Mrreivax ] Bonsoir.Et bien voila. J'ai créé une classe de gestion des images.J'ai par la suité créé une autre classe de gestion de banières.Mais, cette dernière templates avec poo [ par lesnes ] bonjours je reprogramme totalement mon site en poo et je souhaiterai utiliser les templates mais l'on ne peut pas faire appel a une class exterieur a Class POO retourné le nom de l'objet [ par MeTh ] Bonjour,Comment retourné le nom de l'objet déclaré?exemple :$monobjet = new GridR();comment recuperé $monobjet dans ma class?Merci Include, class et array [ par Hades5k ] Bonjour! J'ai un petit problème à utiliser un array dans un fichier que j'inclus... voici un peu le code : &lt;?php $classNames = array(); include_onc Problem d'affichage de resultat de requete sous forme de tableau [ par jbcaiz ] explication : je fais un requete de recherche dans ma base, qui doit normalement me sortir plusieur résultat.je veux que ces résultat s'affiche dans u OBJECT EMBED + BLOB [ par RealKEV1 ] Bonjour,Je récupére grace à php un objet .wmv crypté type LongBlob ( stocké dans une table mysql). Et je voudrais faire une page html spéciale pour po OBJECT EMBED + BLOB WMA [ par RealKEV1 ] Bonjour,Je récupére grace à php un objet .wma crypté type LongBlob (stocké dans ma table mysql). Et je voudrais faire une page html spéciale pour pouv Serveur SMTP [ par Marion0904 ] Bonsoir, J'essai d'nvoyer des mails en utilisant la class phpmailer (disponible sur&nbsp; http://phpmailer.sourceforge.net/). J'incu la class php mail AU SECOURS ! (je suis prêt à me jeter par la fenêtre) [ par nougitch ] Bonjour, Je poss&#232;de un tableau. J'aimerai que quand je clique sur une donn&#233;e elle se colore. Quand quand je reclique dessus, elle retrouve class,PDF,XLS et boucles..... [ par booth ] bonjour!j'ai un méga problème...je dois générer un PDF et une grillle excel toutes deux issues d'un moteur de recherche...pour le moteur de recherche


Nos sponsors


Sondage...

Comparez les prix

CalendriCode

Mai 2012
LMMJVSD
 123456
78910111213
14151617181920
21222324252627
28293031   

Consulter la suite du CalendriCode

A découvrir



 
Développement réalisé par Nicolas SOREL (Nix) avec l'aide de : Cyril DURAND et Emmanuel (EBArtSoft), Merci à Vincent pour ses précieux conseils.
CodeS-SourceS.com© Toute reproduction même partielle est interdite sauf accord écrit du Webmaster
CodeS-SourceS.com© est une marque déposée tous droits réservés

Google Coop CodeS-SourceS Google Coop CodeS-SourceS
Temps d'éxécution de la page : 0,905 sec (3)

Nous contacter | Annoncer sur CodeS-SourceS | Mentions légales