CakeDC Blog

TIPS, INSIGHTS AND THE LATEST FROM THE EXPERTS BEHIND CAKEPHP

Using CakePHP ORM in your app

CakePHP ORM in your app

We all know that CakePHP is a Full Stack framework, but you may not know that you can pick some of the components and use it in your app when you need. The ORM is not the only one available - you could also have filesystem, validation, utility, core, collection, database, cache, event, form, log, datasource, console and i18n. In this article, we are going to show how to use the ORM component in your slim framework app. You can find the component at: https://github.com/cakephp/?q=read&type=&language=

 

Why should we use the componentes

You may be asking why to use as component instead of using the framework as it is, and one of the reasons would be that you already have an application, perhaps using slim framework, and now you need to retrieve data from database. This would be a good moment to use a lib to help you, and here is where cakephp/orm comes in handy.

With the componentes you can now solve things with your knowledge in CakePHP, even when your application was not built with CakePHP.

 

Setting up cakephp/orm in a slim application

The code used in this article can be found at: https://github.com/CakeDC/slim-cakephp4-packages

We could use the package in any PHP application, but for this article we are going to use a slim application skeleton https://github.com/slimphp/Slim-Skeleton. In this app we’re going to change the routes /users and /users/[id] to fetch data from database instead of in-memory data.

 

Install the package with composer

We are going to install the version 4.0 of the ORM package:

 

composer require cakephp/orm:~4.0

 

Update config

The app uses the file app/settings.php to set up the main configs, so we need to add a config for database and set cakephp’s App.namespace config.

First: add this line after the use declaration. Don’t worry about this config now. We’re setting this to avoid error with PHP 7.4.

 

Configure::write('App.namespace', 'App');

 

Then add your database config key inside settings array - in this case we’re using mysql database from a docker service:

 

            'database' => [

                'className' => \Cake\Database\Connection::class,

                'driver' => \Cake\Database\Driver\Mysql::class,

                'database' => 'my_db',

                'username' => 'root',

                'password' => 'secret',

                'host' => 'mysql',

            ]

 

See https://github.com/CakeDC/slim-cakephp4-packages/blob/main/app/settings.php

 

Add TableLocator to app dependencies

The app uses the file app/dependencies.php to configure the container of dependencies, and this is a good place for us to define TableLocator as dependency since we normally would use it

In my places. Let’s add this inside $containerBuilder->addDefinitions:

 

\Cake\ORM\Locator\TableLocator::class => function(ContainerInterface $c) {

            $settings = $c->get('settings');

            \Cake\Datasource\ConnectionManager::setConfig('default', $settings['database']);

 

            return new \Cake\ORM\Locator\TableLocator();

 }

 

See https://github.com/CakeDC/slim-cakephp4-packages/blob/main/app/dependencies.php

 

 

This service gets the settings we defined before,sets the configuration to CakePHP, and returns an instance of TableLocator.

We could use this service in any route action with: 

 

$locator  = $this->get(\Cake\ORM\Locator\TableLocator::class);

$users = $locator->get('Users')->find()->all()->toArray();

 

But for this app it will make sense to use the TableLocator in a custom persistence class.

 

Using the ORM to fetch data

Now, we are finally going to replace the current way of retrieving data to be able to use CakePHP OR. Since our idea is to have a minimum impact in the app, the best way for this app is to replace the current UserRepository. Keep in mind that you could use the following steps with any other class you have.

 

Create a new persistence class DatabaseUserRepository:

Create the class at src/Infrastructure/Persistence/User/DatabaseUserRepository.php

Define a constructor method with tableLocator parameter

 

    public function __construct(\Cake\ORM\Locator\TableLocator $tableLocator)

    {

              $this->tableLocator = $tableLocator;

    }

        

Now we can use the tableLocator to fetch data:

 

      $this->tableLocator->get('Users')->find()->all();

      $this->tableLocator->get('Users')->get(10);

      ////

 

To make the app work correctly, we need  to add the required method findAll  and findUserOfId

 

See: https://github.com/CakeDC/slim-cakephp4-packages/blob/main/src/Infrastructure/Persistence/User/DatabaseUserRepository.php

    

Now that the repository persistence class was created, we need to connect using dependency injection. Update the UserRepository::class entry in repositories with:

 

UserRepository::class => \DI\autowire(\App\Infrastructure\Persistence\User\DatabaseUserRepository::class),

 

https://github.com/CakeDC/slim-cakephp4-packages/blob/main/app/repositories.php

 

That’s it! Now we can access /users and see the users stored in our database.

 

I hope you’ve found this information to be helpful! Let us know!

For more information check out: https://github.com/cakephp/orm.

Latest articles

Modifying Requests Like A Chef

Since the version 2.x of CakePHP has a requests and response objects, they are provided an abstraction around HTTP Requests and responses. If you are not familiar with CakePHP, it’s a common step when you bake and use $this->request->data instead of $_POST. Most of the time, we need to modify and append values on our Request data. This can be an identifier of logged user or values for any fields. In many situations, implementations will like this: Data can be modified easily - you just need to call withData or withParsedBody method and after set the Request  (you can also modify the query calling withQueryParams): Both implementations will generate the same value, but if you have a keen eye, you will see that the second implementation is more clear. Also, our Request has these values on data. This information can be useful when you use Components from Plugins, as they will expect the values on Requests.   That’s all bakers! I hope this content is useful for you and will improve your requests!  

Where you SHOULD be marketing your business.

Marketing is an essential part of your business’ success. I don’t just say this because I myself am a marketing connoisseur... or maybe I do. But either way, I’m going to shoot you some quick knowledge about getting your name out there... specifically into the cyber world.   

Social media 

Branding is very important here. This will be another blog for another time... but having a uniform look, format, font, etc will help you look professional and stand out. Some of the platforms I work with for our company is Facebook, Instagram, Twitter. In our industry, Twitter is our cake and frosting (see what I did there). Most developers have a Twitter and use this to interact with other developers, frameworks, and companies. Having a company page allows you to engage with your followers, have conversations, and build relationships. Remember, you need to be posting things that are important for those who follow you to see, and when they reach out, be ready to respond.  For business contacts and networking, I am a big fan of LinkedIn. This platform is an easy way to connect and search for others in your field. Also, it's a good way to find people looking for your specific services. Very business. Very professional.  You definitely need to get to know your audience. Tracking your social analytics will tell you where you stand out most. Then, you utilize that information!  

Ads

 I’m a fan of Google Ads. While I know that the idea of paid advertising isn’t ideal or financially possible for everyone, there are other options. Keeping up with your SEO, or search engine optimization, will help with organic ads. Organic ads is a fancy way of saying free clicks, or free adveritsing. When people are searching Google for services or phrases pertaining to your business, then your site will show in the results. Obviously if you pay for ads, you can manually add phrases and terms that may be searched for... and these are called keywords. I think Google Ads pointers may be a good blog for me to share in the future *makes mental note*.    Speaking of Google, make sure your “my Google business” account is up to date, otherwise you will literally NEVER show up on the search engine. Even when someone specifically searches for you or your company.   

Email Marketing

We must be careful here. Gone are the days of spam emailing... and cold calling? Please don’t. I’d say most people are ready to get restraining orders against telemarketers. Just me?  However, if you have specific things (sales, offers, important news) to share with your customer base, then by all means - onward. At least emails can be ignored if they are unwanted. If you want your email to be opened, make sure that you are offering your recipients something worth clicking (specials. Giveaways. Etc.). A good platform to help you with this is MailChimp, but there are soo many ways to generate these emails, and many even offer pre-made templates... so no excuses.   

Newsletters

Similar to email marketing, there are newsletters. The difference here is that the people who will be receiving your monthly (most likely) newsletter are only those that have chosen to. “Subscribers” sign up to receive these emails. Usually, these aren’t offers of sales, but rather news, events, tips etc. You can get an idea of what I mean by checking out the CakePHP Newsletter archives. 
  So let's close with some quick facts: Newspaper advertising? Out Telemarketing? Out  Print? Maybe  Billboards? If the price is right and you are local to certain areas. International companies, like CakeDC do not benefit from this type of print, unless we could put one in every city around the world. I think that would blow my marketing budget pretty quick.  If you are a freelancer, I definitely suggest Fiverr. Let people find you. Essentially you get quality leads for free.    All of these marketing platforms and items need to be explained in deeper detail, so if you have any questions feel free to reach out to me!  

Benefits Of Upgrading

Let’s talk more about upgrading your CakePHP application. In last week’s blog, we talked about why you should hire externally for all of your upgrade needs. You may have been thinking… but why would I (or my company) even need to spend the time, effort, and money on upgrading our projects. Well… for many reasons. You need better security, compatibility, functionality.  You’ve seen our posts, you know what needs to be done. Your old CakePHP application needs to be updated.  I want to remind you about some of the benefits that there is to upgrading.   

SECURITY

The more maintained a CakePHP version is, the more security it can provide. This not only protects the projects themselves, but can also give you peace of mind knowing that the latest versions will be functional a lot longer than say CakePHP 2.x. And of course, the latest releases fix a number of security issues. No company wants to offer quality services to their customers,  and end up with a security breach that was out of their control. It is extremely important to get ahead of the security issues on the front end. Be proactive, and you won’t have to be reactive.  The biggest concern is that many hosting providers are abolishing old PHP branches, essentially overnight. This is why it is important to be aware of when to migrate/upgrade and do it before it is too late. You can see a list of the end of life date for each unsupported branch of PHP HERE.   

PERFORMANCE

CakePHP 4 follows the latest conventions, helping your application run faster and smoother. Old sites / applications run slow… that is no secret. I promise you one thing, today’s Google searcher will not think twice to do a different search if the site is lagging (ain’t nobody got time for that).  Also, migrating to a current PHP release over 5.6 and using the new ORM, could lead to improvements over 50%. So I mean, win-win.    If you are wondering about your performance, speed, or  which versions of PHP you are running on, you can use tools like Pingdom - https://tools.pingdom.com/ or Google Chrome Devtools - https://developers.google.com/web/tools/chrome-devtools.  

SCALABILITY & TOOLS

CakePHP 4 is shipped with best practices to streamline horizontal scaling and deployment into containers. As new tools and plugins are released, they may only be compatible with the latest versions. Currently, there are over 900 updated plugins, see here: https://plugins.cakephp.org/, covering from background job processing, image processing, CMS, file upload and management, cache, and more. This provides more features and results in developers WANTING to use and work with the framework. 

Of course there is a long list of additional benefits, but these are some of the most important. 2021 seems to be turning into the year of upgrades. Don’t get left behind!

We Bake with CakePHP