We start off by creating a new module called FoggylineCatalogBundle
. We do so with the help of the console, by running the command as follows:
php bin/console generate:bundle --namespace=Foggyline/CatalogBundle
The command triggers an interactive process that asks us several questions along the way, as shown in the following screenshot:
Once done, the following structure is generated for us:
If we now take a look at the app/AppKernel.php
file, we would see the following line under the registerBundles
method:
new FoggylineCatalogBundleFoggylineCatalogBundle()
Similarly, the app/config/routing.yml
has the following route definition added to it:
foggyline_catalog: resource: "@FoggylineCatalogBundle/Resources/config/routing.xml" prefix: /
Here we need to change prefix: /
into prefix: /catalog/
, so we don't collide with core module routes. Leaving it as prefix: /
would simply overrun our core AppBundle
and output Hello World!
from the src/Foggyline/CatalogBundle/Resources/views/Default/index.html.twig
template to the browser at this point. We want to keep things nice and separated. What this means is that the module does not define the root route for itself.
Let's go ahead and create a Category
entity. We do so by using the console, as shown here:
php bin/console generate:doctrine:entity
This creates the Entity/Category.php
and Repository/CategoryRepository.php
files within the src/Foggyline/CatalogBundle/
directory. After this, we need to update the database, so it pulls in the Category
entity, as shown in the following command line instance:
php bin/console doctrine:schema:update --force
This results in a screen that looks similar to the following screenshot:
With entity in place, we are ready to generate its CRUD. We do so by using the following command:
php bin/console generate:doctrine:crud
This results with interactive output as shown here:
This results in src/Foggyline/CatalogBundle/Controller/CategoryController.php
being created. It also adds an entry to our app/config/routing.yml
file as follows:
foggyline_catalog_category: resource: "@FoggylineCatalogBundle/Controller/CategoryController.php" type: annotation
Furthermore, the view files are created under the app/Resources/views/category/
directory, which is not what we might expect. We want them under our module src/Foggyline/CatalogBundle/Resources/views/Default/category/
directory, so we need to copy them over. Additionally, we need to modify all of the $this->render
calls within our CategoryController
by appending the FoggylineCatalogBundle:default: string
to each of the template paths.
Next, we go ahead and create the Product
entity by using the interactive generator as discussed earlier:
php bin/console generate:doctrine:entity
We follow the interactive generator, respecting the minimum of the following attributes: title
, price
, sku
, url_key
, description
, qty
, category
, and image
. Aside from price
and qty
, which are of types decimal and integer, all other attributes are of type string. Furthermore, sku
and url_key
are flagged as unique. This creates the Entity/Product.php
and Repository/ProductRepository.php
files within the src/Foggyline/CatalogBundle/
directory.
Similar to what we have done for the Category view
templates, we need to do for the Product view
templates. That is, copy them over from the app/Resources/views/product/
directory to src/Foggyline/CatalogBundle/Resources/views/Default/product/
and update all of the $this->render
calls within our ProductController
by appending the FoggylineCatalogBundle:default: string
to each of the template paths.
At this point, we won't rush updating the schema, as we want to add proper relations to our code. Each product should be able to have a relation to a single Category
entity. To achieve this, we need to edit Category.php
and Product.php
from within the src/Foggyline/CatalogBundle/Entity/
directory, as follows:
// src/Foggyline/CatalogBundle/Entity/Category.php /** * @ORMOneToMany(targetEntity="Product", mappedBy="category") */ private $products; public function __construct() { $this->products = new DoctrineCommonCollectionsArrayCollection(); } // src/Foggyline/CatalogBundle/Entity/Product.php /** * @ORMManyToOne(targetEntity="Category", inversedBy="products") * @ORMJoinColumn(name="category_id", referencedColumnName="id") */ private $category;
We further need to edit the Category.php
file by adding the __toString
method implementation to it, as follows:
public function __toString() { return $this->getTitle(); }
The reason we are doing so is that, later on, our Product-editing form would know what labels to list under the Category selection, otherwise the system would throw the following error:
Catchable Fatal Error: Object of class FoggylineCatalogBundleEntityCategory could not be converted to string
With the above changes in place, we can now run the schema update, as follows:
php bin/console doctrine:schema:update --force
If we now take a look at our database, the CREATE
command syntax for our product
table looks like the following:
CREATE TABLE `product` ( `id` int(11) NOT NULL AUTO_INCREMENT, `category_id` int(11) DEFAULT NULL, `title` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `price` decimal(10,2) NOT NULL, `sku` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `url_key` varchar(255) COLLATE utf8_unicode_ci NOT NULL, `description` longtext COLLATE utf8_unicode_ci, `qty` int(11) NOT NULL, `image` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `UNIQ_D34A04ADF9038C4` (`sku`), UNIQUE KEY `UNIQ_D34A04ADDFAB7B3B` (`url_key`), KEY `IDX_D34A04AD12469DE2` (`category_id`), CONSTRAINT `FK_D34A04AD12469DE2` FOREIGN KEY (`category_id`) REFERENCES `category` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
We can see two unique keys and one foreign key restraint defined, as per the entries provided to our interactive entity generator. Now we are ready to generate the CRUD for our Product
entity. To do so, we run the generate:doctrine:crud
command and follow the interactive generator as shown here:
At this point, if we access either /category/new/
or /product/new/
URL, the image field is just a simple input text field, not the actual image upload we would like. To make it into an image upload field, we need to edit the $image
property of Category.php
and Product.php
as follows:
//… use SymfonyComponentValidatorConstraints as Assert; //… class [Category|Product] { //… /** * @var string * * @ORMColumn(name="image", type="string", length=255, nullable=true) * @AssertFile(mimeTypes={ "image/png", "image/jpeg" }, mimeTypesMessage="Please upload the PNG or JPEG image file.") */ private $image; //… }
As soon as we do so, the input fields turn into the file upload fields, as shown here:
Next, we will go ahead and implement the upload functionality into the forms.
We do so by first defining the service that will handle the actual upload. Service is defined by adding the following entry into the src/Foggyline/CatalogBundle/Resources/config/services.xml
file, under the services
element:
<service id="foggyline_catalog.image_uploader" class="FoggylineCatalogBundleServiceImageUploader"> <argument>%foggyline_catalog_images_directory%</argument> </service>
The %foggyline_catalog_images_directory%
argument value is the name of a parameter the we will soon define.
We then create the src/Foggyline/CatalogBundle/Service/ImageUploader.php
file with content as follows:
namespace FoggylineCatalogBundleService; use SymfonyComponentHttpFoundationFileUploadedFile; class ImageUploader { private $targetDir; public function __construct($targetDir) { $this->targetDir = $targetDir; } public function upload(UploadedFile $file) { $fileName = md5(uniqid()) . '.' . $file->guessExtension(); $file->move($this->targetDir, $fileName); return $fileName; } }
We then create our own parameters.yml
file within the src/Foggyline/CatalogBundle/Resources/config
directory with content as follows:
parameters: foggyline_catalog_images_directory: "%kernel.root_dir%/../web/uploads/foggyline_catalog_images"
This is the parameter our service expects to find. It can easily be overridden with the same entry under app/config/parameters.yml
if needed.
In order for our bundle to see the parameters.yml
file, we still need to edit the FoggylineCatalogExtension.php
file within the src/Foggyline/CatalogBundle/DependencyInjection/ directory
, by adding the following loader
to the end of the load
method:
$loader = new LoaderYamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config')); $loader->load('parameters.yml');
At this point, our Symfony module is able to read its parameters.yml
, thus making it possible for the defined service to pickup the proper value for its argument. All that is left is to adjust the code for our new
and edit
forms, attaching the upload functionality to them. Since both forms are the same, the following is a Category
example that equally applies to the Product
form as well:
public function newAction(Request $request) { // ... if ($form->isSubmitted() && $form->isValid()) { /* @var $image SymfonyComponentHttpFoundationFileUploadedFile */ if ($image = $category->getImage()) { $name = $this->get('foggyline_catalog.image_uploader')->upload($image); $category->setImage($name); } $em = $this->getDoctrine()->getManager(); // ... } // ... } public function editAction(Request $request, Category $category) { $existingImage = $category->getImage(); if ($existingImage) { $category->setImage( new File($this->getParameter('foggyline_catalog_images_directory') . '/' . $existingImage) ); } $deleteForm = $this->createDeleteForm($category); // ... if ($editForm->isSubmitted() && $editForm->isValid()) { /* @var $image SymfonyComponentHttpFoundationFileUploadedFile */ if ($image = $category->getImage()) { $name = $this->get('foggyline_catalog.image_uploader')->upload($image); $category->setImage($name); } elseif ($existingImage) { $category->setImage($existingImage); } $em = $this->getDoctrine()->getManager(); // ... } // ... }
Both the new
and edit
forms should now be able to handle file uploads.
Now let's go ahead and address the category menu and the on-sale items. Back when we were building the core module, we defined the global variables under the twig:global
section of the app/config/config.yml
file. These variables were pointing to services defined in the app/config/services.yml
file. In order for us to change the content of the category menu and the on sale items, we need to override those services.
We start off by adding the following two service definitions under the src/Foggyline/CatalogBundle/Resources/config/services.xml
file:
<service id="foggyline_catalog.category_menu" class="FoggylineCatalogBundleServiceMenuCategory"> <argument type="service" id="doctrine.orm.entity_manager" /> <argument type="service" id="router" /> </service> <service id="foggyline_catalog.onsale" class="FoggylineCatalogBundleServiceMenuOnSale"> <argument type="service" id="doctrine.orm.entity_manager" /> <argument type="service" id="router" /> </service>
Both of the services accept the Doctrine ORM entity manager and router service arguments, as we will need to use those internally.
We then create the actual Category
and OnSale
service classes within the src/Foggyline/CatalogBundle/Service/Menu/
directory as follows:
//Category.php namespace FoggylineCatalogBundleServiceMenu; class Category { private $em; private $router; public function __construct( DoctrineORMEntityManager $entityManager, SymfonyBundleFrameworkBundleRoutingRouter $router ) { $this->em = $entityManager; $this->router = $router; } public function getItems() { $categories = array(); $_categories = $this->em->getRepository('FoggylineCatalogBundle:Category')->findAll(); foreach ($_categories as $_category) { /* @var $_category FoggylineCatalogBundleEntityCategory */ $categories[] = array( 'path' => $this->router->generate('category_show', array('id' => $_category->getId())), 'label' => $_category->getTitle(), ); } return $categories; } } //OnSale.php namespace FoggylineCatalogBundleServiceMenu; class OnSale { private $em; private $router; public function __construct(DoctrineORMEntityManager $entityManager, $router) { $this->em = $entityManager; $this->router = $router; } public function getItems() { $products = array(); $_products = $this->em->getRepository('FoggylineCatalogBundle:Product')->findBy( array('onsale' => true), null, 5 ); foreach ($_products as $_product) { /* @var $_product FoggylineCatalogBundleEntityProduct */ $products[] = array( 'path' => $this->router->generate('product_show', array('id' => $_product->getId())), 'name' => $_product->getTitle(), 'image' => $_product->getImage(), 'price' => $_product->getPrice(), 'id' => $_product->getId(), ); } return $products; } }
This alone won't trigger the override of the core module services. Within the src/Foggyline/CatalogBundle/DependencyInjection/Compiler/
directory we need to create an OverrideServiceCompilerPass
class that implements the CompilerPassInterface
. Within its process method, we can then change the definition of the service, as follows:
namespace FoggylineCatalogBundleDependencyInjectionCompiler; use SymfonyComponentDependencyInjectionCompilerCompilerPassInterface; use SymfonyComponentDependencyInjectionContainerBuilder; class OverrideServiceCompilerPass implements CompilerPassInterface { public function process(ContainerBuilder $container) { // Override the core module 'category_menu' service $container->removeDefinition('category_menu'); $container->setDefinition('category_menu', $container->getDefinition('foggyline_catalog.category_menu')); // Override the core module 'onsale' service $container->removeDefinition('onsale'); $container->setDefinition('onsale', $container->getDefinition('foggyline_catalog.onsale')); } }
Finally, we need to edit the build
method of the src/Foggyline/CatalogBundle/FoggylineCatalogBundle.php
file in order to add this compiler pass as shown here:
public function build(ContainerBuilder $container) { parent::build($container); $container->addCompilerPass(new FoggylineCatalogBundleDependencyInjectionCompilerOverrideServiceCompilerPass()); }
Now our Category
and OnSale
services should override the ones defined in the core module, thus providing the right values for the header Category menu and On Sale section of the homepage.
The auto-generated CRUD made a Category page for us with the layout as follows:
This is significantly different from the Category page defined under Chapter 4, Requirement Specification for Modular Web Shop App. We therefore need to make amends to our Category Show page, by modifying the show.html.twig
file within the src/Foggyline/CatalogBundle/Resources/views/Default/category/
directory. We do so by replacing the entire content of body
block with code as follows:
<div class="row"> <div class="small-12 large-12 columns text-center"> <h1>{{ category.title }}</h1> <p>{{ category.description }}</p> </div> </div> <div class="row"> <img src="{{ asset('uploads/foggyline_catalog_images/' ~ category.image) }}"/> </div> {% set products = category.getProducts() %} {% if products %} <div class="row products_onsale text-center small-up-1 medium-up-3 large-up-5" data-equalizer data-equalize-by-row="true"> {% for product in products %} <div class="column product"> <img src="{{ asset('uploads/foggyline_catalog_images/' ~ product.image) }}" alt="missing image"/> <a href="{{ path('product_show', {'id': product.id}) }}">{{ product.title }}</a> <div>${{ product.price }}</div> <div><a class="small button" href="{{ path('product_show', {'id': product.id}) }}">View</a></div> </div> {% endfor %} </div> {% else %} <div class="row"> <p>There are no products assigned to this category.</p> </div> {% endif %} {% if is_granted('ROLE_ADMIN') %} <ul> <li> <a href="{{ path('category_edit', { 'id': category.id }) }}">Edit</a> </li> <li> {{ form_start(delete_form) }} <input type="submit" value="Delete"> form_end(delete_form) }} </li> </ul> {% endif %}
The body is now sectioned into three areas. First, we are addressing the category title and description output. We are then fetching and looping through the list of products assigned to category, rendering each individual product. Finally, we are using the is_granted
Twig extension to check if the current user role is ROLE_ADMIN
, in which case we show the Edit
and Delete
links for the category.
The auto-generated CRUD made a Product page for us with the layout as follows:
This differs from the Product page defined under Chapter 4, Requirement Specification for Modular Web Shop App. To rectify the problem, we need to make amends to our Product Show page, by modifying the show.html.twig
file within the src/Foggyline/CatalogBundle/Resources/views/Default/product/
directory. We do so by replacing entire content of body
block with code as follows:
<div class="row"> <div class="small-12 large-6 columns"> <img class="thumbnail" src="{{ asset('uploads/foggyline_catalog_images/' ~ product.image) }}"/> </div> <div class="small-12 large-6 columns"> <h1>{{ product.title }}</h1> <div>SKU: {{ product.sku }}</div> {% if product.qty %} <div>IN STOCK</div> {% else %} <div>OUT OF STOCK</div> {% endif %} <div>$ {{ product.price }}</div> <form action="{{ add_to_cart_url.getAddToCartUrl (product.id) }}" method="get"> <div class="input-group"> <span class="input-group-label">Qty</span> <input class="input-group-field" type="number"> <div class="input-group-button"> <input type="submit" class="button" value="Add to Cart"> </div> </div> </form> </div> </div> <div class="row"> <p>{{ product.description }}</p> </div> {% if is_granted('ROLE_ADMIN') %} <ul> <li> <a href="{{ path('product_edit', { 'id': product.id }) }}">Edit</a> </li> <li> {{ form_start(delete_form) }} <input type="submit" value="Delete"> {{ form_end(delete_form) }} </li> </ul> {% endif %}
The body is now sectioned into two main areas. First, we are addressing the product image, title, stock status, and add to cart output. The add to cart form uses the add_to_cart_url
service to provide the right link. This service is defined under the core module and, at this point, only provides a dummy link. Later on, when we get to the checkout module, we will implement an override for this service and inject the right add to cart link. We then output the description section. Finally, we use the is_granted
Twig extension, like we did on the Category example, to determine if the user can access the Edit
and Delete
links for a product.
18.220.1.239