using call_user_func_array()
Results 1 to 9 of 9

Thread: using call_user_func_array()

  1. #1
    Senior Member
    Join Date
    Sep 2011
    Posts
    258

    using call_user_func_array()

    Well I'm having a user validator class, which is instantiated to evaluate user data/inputs and send back error messages if problems are detected. This is the way I design it so far, and I am a bit confused with the call_user_funcs_array(). The script is shown below:

    PHP Code:
    <?php

    class UserValidator extends AbstractValidator{
      
    // The user validator for user and usergroup system

      
    private $user;
      private 
    $usergroup;
      
      public function 
    __construct(User $user$type NULL$value NULL){
          
    // Fetch the basic properties for usergroup
          
          
    parent::construct($type$value);
          
    $this->user $user;
          
    $this->usergroup $user->getgroupobj($user->usergroup);
          
    // Successfully instantiate the user validator object
      
    }
      
      public function 
    validate(){
          
    // The core method validate, it sends requests to different private methods based on the type
          
    if(empty($this->type)) throw new Exception('The validation type is empty, something must be seriously wrong...');
          if(
    is_array($this->type) and !is_array($this->value)) throw new Exception('Cannot have scalar value if the type is an array.');
          if(!
    is_array($this->type) and is_array($this->value)) throw new Exception('Cannot have scalar type if the value is an array.');
          
          
    // Now we are validating our user data or input!
          
    $validarray = array("uid""username""password""session""email""ip""usergroup""money""friends");
          foreach(
    $this->type as $val){
             
    $method "{$val}validate";
             if(
    in_array($val$validarray)) call_user_func_array(array($this$method), array());
          }      
      }
      
      private function 
    uidvalidate(){
          
    // The user id Validator
      
    }

      private function 
    usernamevalidate(){
          
    // The user name Validator
      
    }

      private function 
    passwordvalidate(){
          
    // The password Validator
      
    }
      
      private function 
    emailvalidate(){
          
    // The email validator
      


      private function 
    sessionvalidate(){
          
    // The session validator
      


      private function 
    ipvalidate(){
          
    // The ip validator
      
    }

      private function 
    money validate(){
          
    // The user money validator
      
    }
      
    }
    ?>
    As you can see from the above code, the method to execute is not hard-coded as in most cases. If a match between validator type and method is available, the script will execute a method as planned. I heard all_user_func_array() can be used to execute functions/methods dynamically, if the function/method execution is dynamic. However, the first argument of the all_user_func_array() needs to accept an instance of class, while I am calling it inside a class template. So my questions are:

    1. I pass $this to the argument, is this gonna work?
    2. If not, how can I call a method by assigning a method to a variable?
    3. Incase you do not mind, please lemme know if there is a more efficient way of designing a validator class?

    Id appreciate answers to any of the three questions,

  2. #2
    Senior Member anoopmail's Avatar
    Join Date
    May 2005
    Location
    Hell
    Posts
    241
    $this->$method() should work. see variable functions

  3. #3
    Senior Member
    Join Date
    Sep 2011
    Posts
    258
    Oh really? My goodness, thought it was not that stupid of a question to ask. XD But anyway I am glad there is an easier and more straightforward way to complete the task. Thanks for answering to this thread.

  4. #4
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774
    I have a question, prefaced by saying I don't think what you're doing is wrong. Just trying to understand: Do any of these functions really rely on the state of the object? If not (which it seems not) why not make the functions static? Then you can validate one item by Validator::username($_POST['username']); both inside and outside of the class. Then again maybe I don't know what you're doing since you are loading a User class into the validator so maybe state does matter.
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  5. #5
    Senior Member
    Join Date
    Sep 2011
    Posts
    258
    Well yeah, the current user object is passed as an argument into the validator class constructor, at least for this time being. Upon initialization, the script automatically creates a user object for the current loggedin user, which demonstrates the state of this current user. User input through forms/urls can be invalid, or even modified if you have inspect element or firebug installed. The user object is useful to compare certain user inputs to the actual values, such as username and password.

    For instance, assume a user tries to buy an item from itemshop while modifying the shopping cart form by assigning the username to someone else's, he/she wont get away with this since the current user object(which is designed in a way that cannot be modified) is passed into Uservalidator class. If the script finds out that the input username(which is supposed to be in a hidden field for this case) differs from the actual username, well in some cases the user will be banned or at least receive an error message saying authentication fails.

    I personally do not quite like static methods since they look more like procedural codes. I only use them occasionally, when instantiating objects really aint necessary. If a class has none other than static methods, I simply rewrite a function file that contains a number of non-OOP functions.

  6. #6
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,863
    I don't understand this statement:
    Quote Originally Posted by Lord Yggdrasill
    However, the first argument ... needs to accept an instance of class, while I am calling it inside a class template.
    What's a "class template"? And why aren't you concerned about the other uses of $this that appear in the very same method?

    Also, note (a) that there is a call_user_func function, and (b) static methods can be referred to by name as array('classname', 'methodname').

    Oh, and there is also the __call method, which can come in handy for dynamic method dispatch.

    I personally do not quite like static methods since they look more like procedural codes.
    You say that like it's a bad thing
    Last edited by Weedpacket; 04-16-2012 at 01:06 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

  7. #7
    Senior Member Derokorian's Avatar
    Join Date
    Apr 2011
    Location
    Denver
    Posts
    1,774
    Quote Originally Posted by Lord Yggdrasill View Post
    Well yeah, the current user object is passed as an argument into the validator class constructor, at least for this time being. Upon initialization, the script automatically creates a user object for the current loggedin user, which demonstrates the state of this current user. User input through forms/urls can be invalid, or even modified if you have inspect element or firebug installed. The user object is useful to compare certain user inputs to the actual values, such as username and password.

    For instance, assume a user tries to buy an item from itemshop while modifying the shopping cart form by assigning the username to someone else's, he/she wont get away with this since the current user object(which is designed in a way that cannot be modified) is passed into Uservalidator class. If the script finds out that the input username(which is supposed to be in a hidden field for this case) differs from the actual username, well in some cases the user will be banned or at least receive an error message saying authentication fails.
    This whole explanation sounds very strange to me. If a user shouldn't be able to control another user's cart, why even use a hidden input to identify which user's cart it is? Why not control that with sessions? IE Only the cart belonging to the user whom you are logged in as can be altered. Then there would be no reason to couple the user authentication system with the cart system beyond a simple $_SESSION['userDetails']['id'] or something similar (maybe a User::getID() function) and even that's assuming you are storing the cart in the database. If not you can store the whole cart into the session, then the only chance of collision would be session-hijacking but that is a whole different problem.

    I personally do not quite like static methods since they look more like procedural codes. I only use them occasionally, when instantiating objects really aint necessary. If a class has none other than static methods, I simply rewrite a function file that contains a number of non-OOP functions.
    All OOP uses methods, methods are just functions dependent on its member class' state. Static method / "procedural codes [sic]" are functions that are stateless. IE they perform the same function, no matter what else is going on in the program. If a function always does the same thing with its parameters no matter what else is happening, then there is no reason to tightly couple it with an object anyway.
    Sadly, nobody codes for anyone on this forum. People taste your dishes and tell you what is missing, but they don't cook for you. ~anoopmail
    I'd rather be a comma, then a full stop.
    User Authentication in PHP with MySQLi - Don't forget to mark threads resolved - MySQL(i) warning

  8. #8
    Senior Member
    Join Date
    Sep 2011
    Posts
    258
    @Weedpacket:
    I see, thanks for bringing this up for me. I am not quite familiar with using call_user_func and call_user_func_array, and guess I made some stupid mistakes here. Its good to know all these stuff though.

    umm I wont say procedural is bad, just amateur if you ask me.

    @Derokorian:

    I am sorry that was a bad example. There is no need to pass user money as a hidden field in a form if the user money(as a property of user object) will be passed into validator's constructor. I do believe the user object's state is important at least in some cases, but if in the end I cannot find an example I will just drop this idea I come out with.

    Well I am not saying I do not use static methods at all, and in fact I have them in most of my classes. I was just talking about the circumstance in which a class has no member properties and methods(and as a result, only constants, static properties/methods). An example is like this below:

    PHP Code:
    class Foo {
            static public 
    $Name "Alex Roxon";
            static public function 
    helloWorld() {
                print 
    "Hello world from " self::$Name;
            }

    To me it is pointless to write a class without member methods, but others may think otherwise.
    Last edited by Lord Yggdrasill; 04-16-2012 at 02:22 PM.

  9. #9
    Pedantic Curmudgeon Weedpacket's Avatar
    Join Date
    Aug 2002
    Location
    General Systems Vehicle "Thrilled To Be Here"
    Posts
    21,863
    Quote Originally Posted by Lord Yggdrasill
    just amateur if you ask me.
    You say that like it's a bad thing


    I don't see what this UserValidator achieves; it's so tightly bound to the particular implementation of a User that those validation methods might as well be methods of the User object itself. Indeed, such an object could provide its own list of validation checks to a validator which can pick and choose which tests to make.
    Last edited by Weedpacket; 04-16-2012 at 10:59 PM.
    THERE IS AS YET INSUFFICIENT DATA FOR A MEANINGFUL ANSWER
    FAQs! FAQs! FAQs! Most forums have them!
    Search - Debugging 101 - Collected Solutions - General Guidelines - Getting help at all

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •