N
N
nohup2021-02-02 19:49:24
symfony
nohup, 2021-02-02 19:49:24

The problem with the route in the controller. Bug?

Hello. I am new to PHP, OOP, frameworks. I can already do something simple, but I continue to study the language itself, patterns and frameworks, respectively. I decided to immerse myself in Symphony, in general I like everything, I can do primitive things. But there was a problem with Routing, I ask for help in solving and, if possible, explaining "what and how":

There is a class:

class ProductController extends AbstractController
{
    /**
     * @Route("/product/{id}", name="product")
     */
    public function show($id,ProductRepository $productRepository)
    {
        //это я тут уже извращался как мог с условием
        if (!$productRepository->findOneBy(['id' => $id]) && !(int)$id ) {
            throw new NotFoundHttpException('The product does not exist');
        }
        
        return $this->render('product/product/index.html.twig',
        ['product' => $productRepository->findOneBy(['id' => $id])]
        );

    }
}


Displays products by id by going to the address: "site.ru/product/3"
If there is such an id - everything is OK, it will display this product. If not, everything is OK, we can return an error, saying that there is no such page. What's the problem: if we go to an address that starts with the id of an existing product and then add any more characters, it will still find the product by the id that the address started with. Example: "site.ru/product/3askdjhaksj" - will give us a page with a product under id 3. If we enter "site.ru/product/3123123" then, of course, it will not return anything.

Tried like this, didn't help:

public function show(int $id, ProductRepository $productRepository)

//или

public function show(string $id,ProductRepository $productRepository)


How to win it?

Thank you!

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question