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 Enhancing a Simple PHP Application Refactoring the Codebase Separating Concerns: MVC

Johnatan Guzman
PLUS
Johnatan Guzman
Courses Plus Student 2,360 Points

Extra credit: how to do it?

I use this code in the shirt.php file

<?php
    $id = $_GET["id"];
    $product = get_product($id);

    if(!isset($product)) {
        header("location: " . BASE_URL . "shirts/");
        exit();
    }

and this in the products.php file

<?php
function get_product($shirt_id) {
    if (isset($shirt_id)) {
        $product_id = $shirt_id;
        if(isset($products[$product_id])) {
            return $product = $products[$product_id];
        }
    }
}

But it fails everytime, that is, it always goes back to shirts page, which means that the $product variable isnt set by calling my function in the shirt.php file. I come from javascript, and im quite confused to why my code isnt working.

Aaron Munoz
Aaron Munoz
11,177 Points

I'm still trying to solve this with the best practices . It's still confusing to me how to separate controller from model. But if I'm looking at this correctly, the code at the top.

$id = $_GET["id"];
$product = get_product($id);

Should not be in the controller but rather in the model. Wouldn't you say?

1 Answer

Andrew Shook
Andrew Shook
31,709 Points

Johnatan Guzman, can you post all the code from the product.php file. I think the problem may be that your get_product function isn't able to access you products array.

Johnatan Guzman
Johnatan Guzman
Courses Plus Student 2,360 Points

Oh silly me, I added the line $products = get_products_all() inside the get_product function; And now it works as intended! Thanks!

Andrew Shook
Andrew Shook
31,709 Points

No problem, glad I could help.

Johnatan Guzman
Johnatan Guzman
Courses Plus Student 2,360 Points

I actually changed it now as a parameter

$products = get_products_all();
    $id = $_GET["id"];
    $product = get_product($id, $products);

that worked also