Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

PHP Build a REST API with PHP Endpoints and Routing Route Groups

Brandyn Lordi
Brandyn Lordi
17,776 Points

what is use($app) for?

And why is it needed?

Dpecifically this snippet:

$app->group('/api/v1/courses', function() use($app){
    $app->get('', function (Request $request, Response $response, array $args) {
        $result = $this->course->get_courses();
        return $response->withJson($result, 200, JSON_PRETTY_PRINT);
    });
    $app->get('/{course_id}', function (Request $request, Response $response, array $args) {
        $result = $this->course->get_course($args['course_id']);
        return $response->withJson($result, 200, JSON_PRETTY_PRINT);
    });
    $app->group('/{course_id}/reviews', function() use($app){
        $app->get('', function (Request $request, Response $response, array $args) {
            $result = $this->review->getReviewsByCourseId($args['course_id']);
            return $response->withJson($result, 200, JSON_PRETTY_PRINT);
        });
        $app->get('/{review_id}', function (Request $request, Response $response, array $args) {
            $result = $this->review->getreview($args['review_id']);
            return $response->withJson($result, 200, JSON_PRETTY_PRINT);
        });
    });
});

1 Answer

Alena Holligan
STAFF
Alena Holligan
Treehouse Teacher

You are creating an anonymous function (an inline function that is only used in this particular spot)

function() use($app){
...
}

The use($app) portion makes that object available to the anonymous function.