klein / klein.php

A fast & flexible router
MIT License
2.66k stars 290 forks source link

How to create your function $service->callback #330

Closed DimNS closed 8 years ago

DimNS commented 8 years ago

How to create your own function to use into $service->callback($arg1, ...) // Call a user-defined helper

code for all routes

$klein->respond(function ($request, $response, $service) {
            $service->mycallback = function() {
                echo 'test';
            };
}

template

<?php $this->mycallback(); ?>

result Call to undefined method Klein\ServiceProvider::mycallback()

dump $this into template

ServiceProvider {#10 ▼
  #request: Request {#38 ▶}
  #response: Response {#46 ▶}
  #session_id: null
  #layout: "..."
  #view: "..."
  #shared_data: DataCollection {#11 ▼
    #attributes: array:7 [▼
      "path" => "/myproject"
      "mycallback" => Closure {#67 ▼
        class: "MyProject\Init"
        this: Init {#3 …}
        file: "C:\Users\DimNS\Documents\GoogleDrive\htdocs\MyProject\src\Init.php"
        line: "220 to 222"
      }
      "uri" => "/user"
    ]
  }
}
DimNS commented 8 years ago

Found the manual php solution.

<?php $this->mycallback->__invoke(); ?>
kenrick95 commented 5 years ago

Just encountered this, and found a similar StackOverflow question. Adding a solution from that SO question:

<?php ($this->mycallback)(); ?>