Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

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

Brandyn Lordi
Brandyn Lordi
17,778 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.