Working with hierarchical data

Asked

Viewed 147 times

1

I’m creating a system where administrators will set user permissions. As I want to do in an organized and very detailed way, I thought of creating permissions by groups, hierarchically, in this way:

  • Item 1
    • Register
    • Alter
    • Delete
  • Item 2
    • Same thing as Item 1
      • But it may contain more knots
        • And even more if necessary :)
  • Item 3

Ok, the logic is created and the database too, but how to handle it in php?

I would not like to have to limit the amount of us, so it would have to be a dynamic way of consulting. How can I do this?

  • I answered without comment the part of the user groups, as you wrote that the logic and the database is already defined so I think that part of grouping users and giving the same access to this group is already solved, if you don’t let me know that I edit my post complementing this part

2 answers

1

Good morning Diego, I believe that the best way for you to do this is to separate users by status that would be nothing more than groupings of permissions.

This way you would have two streams on your system, a screen in which the Administrator would create status, example (Administrator, Editor, Operator) and another screen in which the System Administrator would link permissions to each status for example: Administrators have full control, Editors can edit and create, Operators can just view.

It is worth noting that the permissions could not be created from the panel, since there would be no way to predict in your system script a permission that does not exist.

Thanks, I hope I helped. Hug.

  • This was my first idea actually, but groups would not be efficient in this case, otherwise I would have to create many groups. I would like to give individual permission and as the system will have several fields, you will need this tree. I’m going to use this logic also in a side project of a virtual store to make the product categories, so anyway I need this tree. But thanks for the reply.

1


I have an implementation that goes against what you want, but to explain I’ll go by parts:

The final result would look like this: (in red is not allowed in green with permission) inserir a descrição da imagem aqui

Well you said that the part of the database is ready, but did not show then I will show how I set there in the database.

    CREATE TABLE `tab_modulo` (
  `mod_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'PK',
  `mod_tipo` varchar(45) NOT NULL COMMENT 'MENU -> MENU DO SISTEMA\nMENU-SUB -> SUB-MENU DO SISTEMA\nMODULO -> MODULO DO SISTEMA\nMODULOUP -> MODULO QUE CONTEM NIVEIS DE ACESSO\nNIVELUP -> NIVEL DE CESSO DENTRO DE UM MODULO',
  `mod_nome` text NOT NULL COMMENT 'tag para visualização no html',
  `mod_apelido` varchar(45) NOT NULL COMMENT 'Nome do Menu/Sub-Menu, nome que aparece na interface permissões etc.',
  `mod_ref` int(11) NOT NULL COMMENT 'Usado para referenciar os sub-menus a qual menu(mod_id) ele pertence',
  `mod_atalho` char(1) DEFAULT NULL COMMENT 'tecla de atalho',
  `mod_ordem` int(11) NOT NULL DEFAULT '0 para ficar em cima na ordenacao e valores positivos irão fazer descer o item na ordenacao',
  PRIMARY KEY (`mod_id`)
) ENGINE=InnoDB AUTO_INCREMENT=116 DEFAULT CHARSET=latin1 COMMENT='Modulos e Menus do sistema';

Understanding the concept:

  • MENU - part that appears without passing the mouse ( this in gray image)
  • SUB-MENU - Part where the modules are grouped ( sub-title if you prefer )
  • MODULE - The page that will be given access ( has the checkbox ahead )
  • MODULE UP and LEVEL UP - Special permissions within a module ( appears as a sub-item of a module )

        mysql> select * from tab_modulo limit 4;
    +--------+----------+---------------------------------------------------------------------------------------+----------------+---------+------------+-----------+
    | mod_id | mod_tipo | mod_nome                                                                              | mod_apelido    | mod_ref | mod_atalho | mod_ordem |
    +--------+----------+---------------------------------------------------------------------------------------+----------------+---------+------------+-----------+
    |      1 | MENU-SUB | <b>Carta Frete</b>                                                                    | Carta Frete    |      42 | c          |         4 |
    |      2 | MENU     | <b>Financeiro</b>                                                                     | Financeiro     |       0 | f          |         1 |
    |      4 | MENU     | <b>Administrador</b>                                                                  | Administrador  |       0 | a          |         6 |
    |      5 | MODULO   | <a href="javascript:loadContent('#conteudo','consultaFrete.php');">Consulta Carta</a> | Consulta Carta |       1 | c          |         0 |
    +--------+----------+---------------------------------------------------------------------------------------+----------------+---------+------------+-----------+
    

I left an attribute with markings TAG when php is going to put the menu already right on the page, and an attribute with the tag-less description to generate the permissions list for me to keep checking/unchecking permissions.

in php I made a function to generate the menu like this:

    private function construirMenuPermissoes(){
    for ($i=0; $i <sizeof($this->objeto); $i++) {   
        if($this->objeto[$i]->mod_tipo == 'MENU'){    //ENTÃO ELE É UM MENU PRINCIPAL
            $this->menus[] = $this->objeto[$i];                
            $mod_id = $this->objeto[$i]->mod_id;
            $mod_apelido = $this->objeto[$i]->mod_apelido;             
            $mod_nome = $this->objeto[$i]->mod_nome;
            $menu = "<div id='p$mod_id' mod_id='$mod_id' class='div-menu'><ul style='width: 180px;'>".
                   // "<li id='".$mod_apelido."'>".
                        "<legend class='ui-widget ui-widget-header ui-corner-all legend'>$mod_nome</legend>?".
                        "<ul id='browser' class='treeview ".$mod_apelido."' style='margin-top: -10px;'>"; //cria o menu no nivel principal
            $itens = "";
            $itens = $itens.$this->getSubNiveis2($mod_id);                
            echo $menu.$itens."</ul></ul></div>";
        }
    } 
}

private function getSubNiveis2($mod_id){ //FUNCAO RECURSIVA USADA NO PERMISSOES.PHP
    for ($i=0; $i < sizeof($this->objeto); $i++) {      
        $mod_apelido = $this->objeto[$i]->mod_apelido;            
        $mod_ref = $this->objeto[$i]->mod_ref;
        $mod_tipo = $this->objeto[$i]->mod_tipo;   
        $id = $this->objeto[$i]->mod_id;
        if( $mod_ref == $mod_id){
            if($mod_tipo == 'MENU-SUB'){
                $menu = @$menu."<li id='p".$id."' mod_id='$id' ><b>".$mod_apelido."</b><ul>";
                $menu = @$menu.$this->getSubNiveis2($id)."</ul>"; //MOD_ID DO ARRAY NAO DO PARAMETRO
            }               
            else if($mod_tipo == 'MODULOUP'){                                // ACESSO ELEVADO DENTRO DE UM MODULO
                $menu = @$menu."<li id='p".$id."' style='padding-bottom: 6px; font: bold 8pt Arial;'><b>".$mod_apelido.
                        "<input class='".$id."' type='checkbox' style='float: right; cursor: pointer;'/>".
                        "</b><ul>";
                $menu = @$menu.$this->getSubNiveis2($id)."</ul>"; //MOD_ID DO ARRAY NAO DO PARAMETRO
            }
            else{                    
                $menu = @$menu."<li id='p".$id.
                        "' style='padding-bottom: 6px; font: bold 8pt Arial;'>".$mod_apelido.
                        "<input class='".$id."' mod_ref='" . $mod_ref . "'
                            type='checkbox' style='float: right; cursor: pointer;'/>"."</li>";
            }
        }
    }
    return $menu;
}

Where $this->object is the array of all modules I have registered in the database. I hope it helped you, doubt the layout.

  • In that case NIVELUP would be the last possible level right?! (The equivalent of Travar Lançamentos second column). The logic is a bit similar, but I need to give space for more knots if I need to, I will need to reuse this code for a system of categories of a store that will have much more knots, so I already want to develop it in the best way possible. Thanks for the info, I’ll just wait a little longer before closing :)

  • @Diegomachado does not exist last level, this NIVELUP is for example a person has access to a module, but within this module for example one can record another only view, nothing prevents you from creating other MENU-SUB, as many times as necessary

  • The Secret is to make the mod_ref attribute receive the mod_id from the node on top, so you can do as many sub-menu as needed

  • Got it, on my table I got the field parent_id which equals to mod_ref. I will finish my code and apply some ideas I took from yours. As soon as I finish putting the result.

  • ok, just to complete what was said follow the example link http://i.imgur.com/jGsfkgQ.png

  • Now everything is ok! It was much simpler than I thought, rs.. But programming is like this, there are easy things that sometimes do not get in the head :) Hugs! Edit: The bonus can only be granted in an hour I don’t know why. Just wait

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.