CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

The updates that CakePHP 3 brings to the table – why we love it and so should you!

 

With a year under its belt and 34 releases, we are still in love with CakePHP 3; and some of you are already on board and loving it. With an average of nearly 3 releases a month, you can easily tell that the team is working against a rapid release cycle where they are tirelessly working at adding and improving features. - but do you know the philosophy behind it?

Looking at all of the improvements and benefits that this updated framework brings, you can clearly see that the biggest turning point for the core team was the increased functionality with clear foresight and thinking brought to the table. A plan was had right from the start, to be a framework well documented, one that was simple (as the Core Team live by – less lines the better!). Another big input from the team, was the ability to integrate and make newer versions of PHP compatible with the framework, never before has the movement in the code base been so fast paced. And as the team comments, this is brought to the fore by the rotating code between open source teams – truly, we live in a space where without each other’s contributions to the code base there would be no movement and action.

That is why we are in love with CakePHP 3, because the team have put forward a framework that integrates, pulls in outside assistance, accepts community help and specifically puts itself out there for the community’s input.

Some quick backgrounds to the updated framework. The first commit to CakePHP 3 was done on May 24 2012, by Juan Basso. A long time coming, but as the common phrase goes, good things come with time. – that and the fact that the core team and lead developers were working in their spare time, after work, late nights, to bring this forward.

We thought that we would reflect, and bring to you the top changes/improvements/benefits/total awesomeness of this framework!

  • All of the core feature development was done as pull requests. This was done intentionally, to encourage people to get involved and the main core team is distributed across the world. The community is vital to the framework, and without them, we wouldn’t be here!

  • To give you an idea of what this has meant. It ended up with over 6000 commits before launch! – from over 20 contributors.

  • CakePHP 3 documentation had over 1500 commits – from 51 contributors! – the document writing was so important to the team, every time there was a feature or a break in backwards compatibility, it was documented.

  • More big news for CakePHP 3 is that it targets PHP 5.5 and newer. It is designed with composer support (Although you don’t need to use composer). It has also required a couple of additional extensions (the mb_string and the intl extension) – this was for 2 reasons, we were handling multi-byte internally, if you didn’t have the mb_string extension, we would fall back to pure PHP code; and for internationalization - there are really powerful tools built into the language that CakePHP 2 wasn’t capitalizing on and the team wanted to leverage those tools – to give the CakePHP community better tools.

  • Now the entire CakePHP code is Unicode aware, and additionally through the intl extension, everything is localized. All of the core classes localize depending on your locale (so if you switch your locale to Germany..) – everything will work, your numbering, date formatting, language formatting (provided you have the translation file) etc.

Over above these changes (and associated benefits), a few other things came out of the cracks..

Such as, through the use of composer, you have to have separate repos for separate things - so the team created a new app skeleton, basically this is the app directory of the old framework but in a separate repo. – What this allows you to do is mold or easily customize and fork it when you want to pull in changes. You don’t have to worry about merge conflicts with the app directory or similar types of issues.

It also gives us the ability to release them independently in the future, so for instance, the app can be upgraded and add or remove dependencies while having no need to modify the framework.

Many of us have had that experience and confusion of configuring classes; you don’t know if it’s a property or method, or even what the method name is.

Well getting more into the detailed features, we all know that there were a lot of different method names for configuring things, some classes used properties, others used methods of various names.

For CakePHP 3 however, it was decided that this is a little silly, so all of the static/instance/runtime classes use one method called config (YAY!). More can be found at http://book.cakephp.org/3.0/en/development/configuration.html

The ORM has also been replaced, we have moved on with the model layer, and CakePHP has advanced quite a bit over the past years. Now you have Tables and Entity objects (no more arrays!), and a powerful Query class to build your queries using a fluent interface. You'll be amazed how easy is to create deep filters, custom finders (and stacking!), subqueries. Validation was also refactored, improving flexibility and customization.

The router was also noted as being a performance bottleneck for a lot of applications in the past, and it was also, somewhat, verbose when you were connecting a lot of routes.

So with CakePHP 3, the old way of connecting routes is still there, but a new scope system has been added. This allows you to declare routes in a much clearer way – so if you have a common prefix, you can put this in the scope, and don’t have to re-declare this in each route. Less typing necessary, but more importantly it allows you to partition your routes so that you can create a much faster parse tree.

A lot of work has also been done on fixing reverse routing, previously it was based on a linear search but now, the key parts of the route are taken (the action or controller name) and generate a list of what that route may be and then search a much smaller subset of routes.

Another change is the helper layer. Previously HTML formatted through arrays, and that had both good and bad points.

The team got rid of the sprintf and replaced it with a very simple templating system, that has no conditions. This lets you define templates file, and you consistently use those templates throughout. This also yields a bit of a performance gain and it doesn’t use number replacements, it uses named replacements.

The way the event subsystems were handled is another change that CakePHP 3 brings to the table, allowing a much more consistent approach to handling events. The new changes have also led to another performance enhancement!

The framework has also gotten some outside help - in the past CakePHP has been criticized for being insular and not making use of the existing ecosystem. This has since changed and one of the reasons was the team wanted to make the install really easy. Because composer is now being use, you can include dependencies and when you create your application or install your applications dependencies, CakePHP 3’s can be installed at the same time.

CakePHP 3 has used:

Chronos (A fork of Carbon) has been used for date time improvements, (but now its part of CakePHP itself and maintained by the core)

Aura/Intl – improved i18n and L10n features

A great wrap up to these things is the fact that the team has hugely increased functionality and features, while keeping performance constant (in most cases, actually increasing it!!). There are so many reasons that you should start and continue using CakePHP 3 but more importantly, there are so many reasons for being a part of this insanely great, collaborative community.

Latest articles

CakePHP Query Builder

CakePHP’s  database Query Builder provides a simple to use fluent interface for creating and operating database queries. It can be used to accomplish most database operations in your application, and works on all supported database systems.
Query builders allow us to create database queries that work with any supported database, without having to worry about differences between SQL implementations in the different database systems.


The CakePHP query builder uses PDO parameter binding to protect your application against SQL injection attacks. There is no need to clean strings being passed as bindings.
For creating a Query object in CakePHP, the easiest way is using find() from a Table object. In CakePHP, queries are lazily evaluated,  which means that they are not evaluated until any of the following actions happens: the query is iterated through a foreach, it’s called first(), all(), toList(), toArray(). 
You can check all the SQL queries that CakePHP is generating, you just need to enable the Database Logging. See here:  https://book.cakephp.org/4/en/orm/database-basics.html#query-logging
Let’s do a few samples using the Query Builder - this is the ER diagram of the database that we will be using for the queries. We have Orders, ProductsUsers and Items that will store the products sold in each order and the quantity sold. Let’s create some queries using the Query Builder SQL Functions: https://book.cakephp.org/4/en/orm/query-builder.html#using-sql-functions. SQL Functions as part of the Query Builder are abstractions of  some commonly used SQL functions,  and they allow the ORM to choose the specific implementation your application needs based on the Database that is being used. For example, CONCAT is implemented in a different way in MySQL and Postgres, using concat() function will work if you use MySQL or Postgres   Imagine we want to build a report of the products sold, including the following:

  1. Display the product in the following format “Products.name - Products.description”.
  2. Total of products sold.
  3. Total of products in stock..
  4. Total amount on sold products.
First, we need to build the Query object using find(), this needs to be done from the Table. $query = Table->find();. We want to get a report of the products sold and the current stock. Initially, we would need to build a subquery using ItemsTable where the information related to the products sold is present.  Don’t forget to use identifier() when referencing any column. This will tell us  the items sold per product. 

$itemsQuery = $this->Items->find() ->where(['Items.product_id' => $query->identifier('Products.id')]);

Now, let’s build each query needed for the information required:
  1. Let’s start displaying the  product in the following format: “Products.name - Products.description”. Using concat() we could get it: $query->select([             'display_name' => $query->func()->concat([                 $query->identifier('Products.name'), ' - ',  $query->identifier('Products.description')]),         ]);
  2. Total of products sold. Using sum() we could get it, we just need to sum Items.quantity per each product,  this  is why we use $itemsQuery and then we sum the quantity per each product. $query->select([
      'quantity_sold' => $itemsQuery->select(['sum' => $itemsQuery->func()->sum($query->identifier('Items.quantity'))]),
    ]);
     
  3. To get the income, we need to multiply the Quantity of items  *  Price  and sum all of them.    $query->select([
              'income' => $itemsQuery->select(['sum' => $itemsQuery->func()->sum($query->newExpr('Items.quantity * Items.unit_price'))
                ])]);
     
  4. Stock. to get the stock we need to take advantage of the quantity_sold we just got in #2, and subtract it from the real quantity Products.quantity. For getting this, we would need to create a subquery in the FROM clause using the previous queries, and then subtract in the target query something like quantity - quantity_sold. $products = $query->cleanCopy()->select([
                'id' => 'ProductDetails.id',
                'price' => 'ProductDetails.price',
                'quantity' => 'ProductDetails.quantity',
                'display_name' => 'ProductDetails.displaye_name',
                'quantity_sold' => 'ProductDetails.quantity_sold',
                'income' => 'ProductDetails.income',
                'stock' => $query->newExpr('ProductDetails.quantity - ProductDetails.quantity_sold'),
            ])->from([
              'ProductDetails' => $query->cleanCopy()->select([
                    'id' => 'Products.id',
                    'price' => 'Products.price',
                    'quantity' => 'Products.quantity',
                    'display_name' => $query->func()->concat([$query->identifier('Products.name'), ' -  ', $query->identifier('Products.description')]),
                  'quantity_sold' => $itemsQuery->select(['sum' => $itemsQuery->func()->sum($query->identifier('Items.quantity'))]),
                  'income' => $itemsQuery->cleanCopy()->select(['sum' => $itemsQuery->func()->sum($query->newExpr('Items.quantity * Items.unit_price'))]),           ])
        ]);
     
Notice that we are using cleanCopy(), this is useful when the same Query object is affected previously by a select(), from() or where clauses, if you run this same example without using cleanCopy() you will get unexpected results.  The SQL query generated is this: SELECT ProductDetails.id AS id, ProductDetails.price AS price, ProductDetails.quantity AS quantity, ProductDetails.display_name AS display_name, ProductDetails.quantity_sold AS quantity_sold, ProductDetails.income AS income, (ProductDetails.quantity - ProductDetails.quantity_sold) AS stock FROM (SELECT Products.id AS id, Products.price AS price, Products.quantity AS quantity, (CONCAT(Products.name, :param0, Products.description)) AS display_name, (SELECT (SUM(Items.quantity)) AS SUM FROM items Items WHERE Items.product_id = (Products.id)) AS quantity_sold, (SELECT (SUM(Items.quantity * Items.unit_price)) AS SUM FROM items Items WHERE Items.product_id = (Products.id)) AS income FROM products Products) ProductDetails
CakePHP QueryBuilder gives a ton of possibilities to create queries with clean and robust code. So go play with it and enjoy!  

Are you ready for PHP 8?

In just two days we will get a new PHP release, PHP 8. It’s been almost  5 years since PHP 7 was born and now we are about to enjoy the new major version, which will include some breaking changes and performance improvements.   It comes with a lot of new features, including:  

  • PHP JIT
  • Union types
  • Named arguments
  • Attributes
  • Match expression
  • Constructor property promotion
  • New static return type
  • New mixed type
  • Throw expression
  • Inheritance with private methods
  • Weak maps
  • Allowing ::class on objects
  • Non-capturing catches
  • Trailing comma in parameter lists
  • Create DateTime objects from interface
  • New str_contains() function
  • New str_starts_with() and str_ends_with() functions
  • New fdiv() function
  • New get_debug_type() function
  • New get_resource_id() function
  • Abstract methods in traits improvements
  • Object implementation of token_get_all() 
  • Variable syntax tweaks
  • Type annotations for internal functions externals
  • ext-json always available
  We will explain some of these features in future posts.   Remember that PHP 7.4 active support will remain until November 2021, with security fixes until November 2022. PHP 7.3 active support is almost over and the team will provide security fixes for 1 more year. Finally, PHP 7.2 is already out of active support, and almost out of security fixes (in 5 days). If you want to check PHP versions and support you can go HERE.   So, Are you ready for PHP 8?  

The Making of a Marketing Plan

Listen, although 2020 felt like it lasted 25 years, it’s still hard to believe that we are wrapping up this roller coaster of 12 months.  As companies prepare for 2021, crossing their fingers and wishing for a better Q1… it is important to start thinking about marketing strategies and plans for the next year. Without ideas and a solid goal for your company, it is very unlikely that things will change.   Reasons that making a marketing plan is important:  1. It organizes your goals and provides clear plans of actions to achieve them  2. It keeps everyone on track and on the same page  3. Promotes motivation and accountability
  I know making a marketing plan can sound time consuming, and a little complex, but it doesn’t have to be! I am going to walk you through the steps of making clear cut goals and plans for 2021 (with some actual examples!).  

1. Brainstorming

Our team is great at making notes of things that need attention, whether it's good or bad. We keep open lines of communication on things that are going well, or may need some extra work. It is important for everything to bring their ideas together, no matter how big or small.  I suggest keeping a notepad with things / ideas you have for your team moving forward, and organize them in a way to present to your marketing team.  

2. Team meeting

Now it is time for a group session to compare ideas, talk about what should be the priorities and get approval on anything needed. These meetings are super beneficial, because it is always refreshing to see if your team’s ideas mimic yours, or perhaps they even have some additional great ideas.   

3. Start building your plan

There are ample amounts of templates and checklists that you can find online to ensure that you’re including important information on your strategy plan. Some of the things I recommend including are:
Of course your main table of contents - easy to view for your team     Company mission - WHO ARE YOU?  
  Product Overview - what are you offering your clients?     Goals / Challenges - we all have them, don’t be shy  

Target market - Who are you working for?       Expansion Plan - how will you make it to the next level?   Upcoming Actions - Making a clear timeline for the next year. It is important to make the timeline obtainable... in other words, don’t make goals that are impossible to meet.   Other important topics include additional small actions, goal timeline, campaign calendars, advertising outlets, social media platforms (and the importance, utilization for each one).  

So making a powerpoint or pdf presentation for your team will allow all of the ideas and goals  to come together and be available in one place. I am a big checklist type of person, so in addition to my marketing plan, I always create a document.   

4. Create a spreadsheet

A spreadsheet doesn't have to be fancy, but it holds the team accountable, and we are able to make notes so that we can track the status of certain actions. This also helps me stay on track, and know what actions need to be executed next.    Something like this for internal works just fine:  
 

5. Budget & Execution 

It is extremely important that your team supports the marketing efforts. It is also important to know what your marketing budget will allow. Will you have additional funds for new goals? Will you need to reduce funds on other outlets to allow for new ideas? These are things that will need to be discussed with your financial department.   This is a good reason to create a marketing metrics / budget spreadsheet to track these items. I will share my examples on this in a future blog.    So, once your team is on the same page, and they have clear goals…. IT’S GO TIME. Start working on your plan of actions and preparing to let them fly. For us, some of our goals will take some prep work, so we are gearing up in Q4. 
  Hopefully, you have helpful ideas that you implement on your marketing plan… maybe it’s something I haven’t thought of (i’d love to hear yours! Email me - amanda.goff@cakedc.com). Either way, I wish everyone good luck on their strategies, and may all of your goals come true in 2021. If you’d like more insight on any of the ideas I have included, feel free to reach out, I’d be happy to chat!   

We Bake with CakePHP