D
D
devastation_kvlt2016-09-21 17:16:22
PHP
devastation_kvlt, 2016-09-21 17:16:22

How to remove copy-paste in Slim Framework with the same code in different routers?

In some routers there is a need to define the variable $args['projectFolder']=...
Instead of copy-paste, I want to define a function "for each router", where variables that are used in more than one router will be defined. How to implement it?
If it is unclear explained, then here is the example of the code
Before:

$app->get('/[upload]', function ($request, $response, $args) {
    $args['projectFolder']=$this->settings['projectFolder'];
    return $this->view->render($response, 'upload.html', $args);
})->setName('main');

$app->get('/show_file/{id}', function ($request, $response, $args){
    $args['projectFolder']=$this->settings['projectFolder'];
     ......
    $args['fileUri']= $fileUri;
    return $this->view->render($response, 'show_file.html', $args);
})->setName('show_file');

After:
UnknownSuperfunction(){
    $args['projectFolder']=$this->settings['projectFolder'];
});


$app->get('/[upload]', function ($request, $response, $args) {
    return $this->view->render($response, 'upload.html', $args);
})->setName('main');

$app->get('/show_file/{id}', function ($request, $response, $args){
     ......
    $args['fileUri']= $fileUri;
    return $this->view->render($response, 'show_file.html', $args);
})->setName('show_file');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-09-22
@devastation_kvlt

Option 1

init_vars(){
    $vars['x']='hello';
    return $vars;
});

$app->get('/[upload]', function ($request, $response, $args) {
    $vars= init_vars();
    return $this->view->render($response, 'upload.html', $args);
})->setName('main');

$app->get('/show_file/{id}', function ($request, $response, $args){
    $vars= init_vars();
    $args['fileUri']= $fileUri;
    return $this->view->render($response, 'show_file.html', $args);
})->setName('show_file');

Option 2
$vars['x']='hello';

$app->get('/[upload]', function ($request, $response, $args) use ($vars) {
    $x = $vars['x'];
    return $this->view->render($response, 'upload.html', $args);
})->setName('main');

$app->get('/show_file/{id}', function ($request, $response, $args) use ($vars){
    $x = $vars['x'];
    $args['fileUri']= $fileUri;
    return $this->view->render($response, 'show_file.html', $args);
})->setName('show_file');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question