0

I am learning Classes and OOP and PDO and all that stuff ( I know legacy php, so, can write php 4.x scripts with messy code ^^ ).

So, started to transform over my base template system to the new code so far so good, sessions and PDO are in classes , pagination system is in a class, users are in a class (basicaly everything).

Here's my question.

I use 2 functions to do a single thing first function is to get the user rights and it looks like this

function u()
{
 if ($_SESSION['loggedin'] == 1)
{
return true;
}
else
{
return false;
}
}

As you can see, it just return true or false based on session (code contains more but is for admin/staff ). Should I also convert this to a class ? or is it useless ? and leave it as a function ?

Then my second function is to get some arrays ( used for group system)

function arr($string, $separator = ',')
{
  //Explode on comma
  $vals = explode($separator, $string);

  //Trim whitespace
  foreach($vals as $key => $val) {
    $vals[$key] = trim($val);
  }
  //Return empty array if no items found
  //http://php.net/manual/en/function.explode.php#114273
  return array_diff($vals, array(""));
}

As this function is only used for the group update and to get info from what groups users are in is it in a function

So my question, as far as i understand OOP does it mean that you write code to make things 'easier', so should I also make a class of those functions to make things easier or is it useless as it makes it harder ?

if (u())
{code code};
if (a());
{admin code}

vs

$u = new User; 
if $u->rank(user){
code code
}
if $u->rank(admin){
admin code
}

Base code can be found here it is to give a idea what I am rewriting to pdo.

Saugat Bhattarai
  • 2,614
  • 4
  • 24
  • 33
PowerChaos
  • 55
  • 1
  • 11
  • i use a autoloader at my index page ( function __autoload($class_name) , for pagination system) and the above permition function to provide acces based on user rights ( those rights are set into a session ) , also my functions use a autoloader to include on every single page ( foreach .. include_once $filename; ) as that simple function just says if you are logged in or not ( user or not ?) , so a class could extend it easyer then if it need extending in the future ( more groups/rights ? ) , in short , it is not a waste then it convert it to a class even if it is a one liner ? – PowerChaos Mar 13 '17 at 15:10

4 Answers4

1

Should i rewrite a simple function to a class?

  • Will this make your code maintenance easier?
  • Is this function occuring on more than one place in your project?

I can't give you an absolute answer, however generating an Object Class in PHP for a static simple function is overkill. It means you need to write more code, and your PHP processor has to do several magnitudes more work for the same - simple - outcome.

If your function occurs just once in your project then NO, you do not need to classify it in any way. This just adds overhead.

But, if you are using this function across multiple scripts and especially if there is a reasonable expectation that this function might need editing/extending in the future, then following Don't Repeat Yourself programming means you could put this function into a Static Class.

In the context of this question I will say more about Static Classes below but other options to remove repetition could be having functions in an include file at the top of your script, this essentially does the same thing as a Static class.

Follow DRY and you can happily copy/paste your function into a Static Class and call that class as required.

Static Classes are not instantiated, and can be used as containers for abstract functions such as the one you are describing, which don't fit neatly elsewhere.

however, there is no conclusive answer without us knowing what you're expecting to do with your project, are you maintaining and developing this or just updating a project without adding new functionality?

There seems a large minority of people obsessive that everything needs to be in a class, regardless of efficiency. Resist this temptation to wrap everything in classes, unless:

  • Does it make your data management easier to modularise?
  • Does it reduce/remove code repetition?
  • Does it make your code easier for you to understand?

Static Class Example:

class StaticClass {
    public static function u() {
         return $_SESSION['loggedin'] == 1;
    }

 }

Usage:

StaticClass::u(); ///returns boolean. 

To be honest your function is so simple that in this specific instance you might as well just code the if statement directly:

if(u()){
    // runs if u comparison returns true
}

becomes:

if($_SESSION['loggedin'] == 1){
    // runs the same comparison as u() but avoids the 
    //function/class overheads
}
Community
  • 1
  • 1
Martin
  • 22,212
  • 11
  • 70
  • 132
  • the users are fixed (user/admin/staff) as it also controll the admin/staff links ( /a ), if not logged in it shows the homepage and it is meant to lock the other pages ( like pass.php ) with out logged in , the script is meant as basic for my other scripts ( as you can see on my github, all based on my base system) , or in short , its the start template with basic functions to make other scripts based on this script, based on this post i should stick to what it does now as no extention is needed yet ( maybe later when ranks become flexible but thats for groups) – PowerChaos Mar 13 '17 at 15:18
  • Is this function occuring on more than one script in your project? – Martin Mar 13 '17 at 15:22
  • users permision is on all scripts ( see /pages/admin on git) that need rights (like home/login page) , the shortcut is used to only show to logged in users or users with right rank ( admin got also a second security ) a demo can be found [here] (http://getadedi.com) that i am rewriting , so the rank check is needed on all pages , group ( arr ) not yet – PowerChaos Mar 13 '17 at 15:26
  • @PowerChaos If you have a class (as you mention) dealing with session and login then I'd suggest adding this function into that class. *or* adding it as a static class so it's a static function available to all pages (as you will be autoloading it) – Martin Mar 13 '17 at 15:28
  • ok thank you, now i got a idea how to handle those things based on the explanation, afer my base convert i going convert my shop system so to make it future proof it is better to put ranks into a class and put the arr in a function until i use it for more then one page , so in short , if it is a single use ( or barely used) then use a function and include it, if it is used more then a couple times , make a class of it to adjust it in the future ? – PowerChaos Mar 13 '17 at 15:37
-1

One day, suppose you decide that you wish to handle both session and token based authentication.

interface AuthInterface
{
    public function isAuthenticated(string $credentials): bool;
}

class SessionAuth implements AuthInterface
{
    public function isAuthenticated(string $user)
    {
        return $_SESSION['loggedin'] == 1;
    }
}

class TokenAuth implements AuthInterface
{
    public function isAuthenticated(string $token)
    {
        // validate token and return true / false
    }
}

So in above example, using classes is very handy. You can now switch out your implementations super easy - and your code should still work.

Writing classes and programming to an interface - enables you to depend on abstractions, not on concretions. It should make your life easier.

If you have a few functions that are like helpers - e.g a custom sorting function - then go ahead and keep as a function. No point going overboard.

Gravy
  • 12,264
  • 26
  • 124
  • 193
-1

I think you should be consistent in what you do, but if a function is really just something like

function u()
{
  if ($_SESSION['loggedin'] == 1)
  {
    return true;
  }
  else
  {
    return false;
  }
}

or if you make it short:

function(u) {
  return $_SESSION['loggedin'] == 1;
}

There is no reason to create a class for a one-liner. Also some inprovements for your arr() function: If you want to apply a callback to all Elements of an array, use array_map()

function arr($string, $separator = ',')
{
  //Explode on comma
  $vals = explode($separator, $string);

  //Trim whitespace
  $vals = array_map("trim", $vals);

  //Return empty array if no items found
  //http://php.net/manual/en/function.explode.php#114273
  return array_diff($vals, array(""));
}
Tobias F.
  • 1,050
  • 1
  • 11
  • 23
-2

It's good to move things into classes, it enables reuse and also you can use an autoloader to only load in the classes you're actually using, rather than PHP parsing all the code. I'd put the first function in a User class or something (pass the session information in as a parameter, don't access that from inside your class) and the second one maybe in a Utils class or something like that?

Lorna Mitchell
  • 1,819
  • 13
  • 22
  • i use a autoloader , also a class for sessions ( it overwrite the global sessions to store in database ) , it is just for me to know if i need to put small things ( or one liners) that get used on all pages but also not , into a class, like permitions based on session ( is admin? or normal user , can acces admin page ? or not ) – PowerChaos Mar 13 '17 at 15:04
  • Yes, I would recommend that you put even the small things into classes. You can put a few existing functions that work on similar areas into one class to keep things together. – Lorna Mitchell Mar 13 '17 at 15:27