Welcome Guest, Not a member yet? Register   Sign In
Creating dynamic functions based on values from database


I was wondering is it possible to generate dynamic functions within controller named after values obtained from URL (which is originally from a database)?

For example:


obviously the 'value1' segment is a function on its own and I was wondering if it is possible to generate the 'value2' dynamically at all?

Many thanks. Smile

[eluser]Pascal Kriete[/eluser]
I'm not sure I understand this correctly. You want segment 2 to be dynamic? Or you want segment 2 to define a new function? The latter isn't possible in php.

Option 1: Routing (docs)
$route = array(
                'default_controller'                    => 'main',
                'scaffolding_trigger'                    => '',

                'value1/(\w+)'    => 'value1/handle_dynamic/$1'
Option2: Remap (docs)
class Value1 extends Controller {

     * Constructor
     * @access    public
    function Value1()

    // --------------------------------------------------------------------
     * Remap function calls
     * @access    private
    function _remap($func)
        // Put already defined functions in here
        $allowed = array('test', 'test2');

        if (in_array($func, $allowed) )
            // Something to handle the second parameter

Let me know if that answered your question at all Wink .

And welcome to CodeIgniter.

Many thanks inparo for your reply.

So its impossible to define new functions, that answered my question. Smile

[quote author="modena" date="1223264074"]Many thanks inparo for your reply.

So its impossible to define new functions, that answered my question. Smile[/quote]

You can still use the _remap function to do something like this http://site.com/username.

class Gateway extends Controller {
    function _remap($dynfunc){
        ( $this->_isAllowed($dynfunc) ) ?
    function _isAllowed($dynfunc){
        //Check is $dynfunc is found on the database, return true/false.
    function run($dynfunc){
        //$dynfunc is passed as a parameter, but since the url won't change is looks like a regular segment.
    function default_action($dynfunc){
        //The $dynfunc is not present in DB, so we run the default action.
        //$dynfunc is passed as a parameter in case you want to perform some logging or to inform the user about it.

You can use regular expressions in your Routes config file to basically create any URL you want, and have them access whichever controller or function you want. You can then check their validity inside the appropriate function.

In php5 you can create functions with __call but i don't see how it would be useful in your case as you already call a function.

[eluser]Phil Sturgeon[/eluser]
You could hold down the bile and cosy up for some eval(); loving! Sick

Theme © iAndrew 2016 - Forum software by © MyBB