开发者

PHP Case switch (efficiency)

The code below ensures that when a user accesses control panel, they are ran through a quick verification process to validate what their entities are. For instance, if a user is level 1 they are only given access to video feed which means nothing else is available to them.

When I look at the code though, I can see video feed being called when case 1 and 3 are called. I would possibly enjoy an alternative to make the code more efficient.

I was told a possible array could make things a little easier but then again this is faster.

    switch ($_SESSION['permission']) {
        case 1: // Level 1: Video Feed
            include ("include/panels/videofeed.index.php");
            break;
        case 2: // Level 2: Announcements / Courses / Teachers
            include ("include/panels/announcements.index.php");
            inc开发者_运维问答lude ("include/panels/courses.index.php");
            include ("include/panels/teachers.index.php");
            break;
        case 3: // Level 3: Announcements / Video Feed / Courses / Teachers / Accounts / Logs
            include ("include/panels/announcements.index.php");
            include ("include/panels/videofeed.index.php"); 
            include ("include/panels/courses.index.php");
            include ("include/panels/teachers.index.php");
            include ("include/panels/accounts.index.php");
            include ("include/panels/log.index.php");       
            break;
        case 4: // Level 4: Teachers
            include ("include/panels/teachers.index.php");          
    }


It's fine the way it is. I think you don't mean "efficiency" when you refer to the "repeated" includes. You mean you could compact your code by using the switch fall-through.

While this might make your code smaller, it has no significant impact of efficiency (the time the script takes to run) and it will actually make the code harder to read. Leave it be.


Frist you may run better if you use require_once if its possible. The second point is to shorten the url it seems that its every include the same.

Maybe try to use it in a function for example:

$permission_id = $_SESSION['permission']

function requireModule($moduleName, $path = 'include/panels/') {
    $moduleName .= '.index.php';
    require_once($path . $moduleName);
}

// if you want you can add an arry for it:

$permissionModules = array(
    array('videofeed'),
    array('announcements', 'courses', 'teachers'),
    array('announcements', 'courses', 'teachers', 'accounts', 'log', 'videofeed'),
    array('teachers')
);

// now we can put it in a more effectiv way

if(array_key_exists($permission_id, $permissionModules)) {
    foreach($permissionModules[$permission_id] as $includes) {
        requireModule($includes);
    }
}

Wrong ? Correct me!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜