Yii2 Insert and Ignore duplicates

February 25, 2017 , ,

One of the things that comes with learning a framework is that we should change a bit the way we work in order to correctly build an app.

One of the frameworks I’ve used the most (on a personal and professional level) is Yii2 and my experience has been excellent – fast, reliable and well maintained.

One of the pain points I got since the beginning is the way the database interaction system works that in the end is quite simple, but only now that I understand it. One of the situations that I had to solve was how to do an Insert/Update, so below here’s a snippet on how to do it.

$model::YourModel::findOne(ID); // findOne() searches for the table key, you can use find()->where('=', 'column', 'name')->one(); to identify the model.

if(!$model):
    $model = new YourModel;
endif;

$model->column_1 = 'text';
$model->column_2 = 123;
$model->save();

The logic is:

  • You try to find if you already have the item in the Databse by calling the findOne(key);
  • If there’s no model, create it from scratch;
  • Assign values to the fields
  • Save

That should really be it, I’m surprised there’s no other documentation explaining this quickly and simple.

Feel free to post any questions below.

Read more »


HTTP vs HTTPS, certificates and website security

I’ve already talked about HTTPS (and HTTP/2) in a recent article, but I would like to emphasize the ways of working, advantages / disadvantages and how you can apply it to your website too in order to protect your your users and ensure data integrity.

What’s the difference between HTTP and HTTPS?

They’re both Hypertext transfer protocols running over TCP  but the latter does it over a Secure Socket Layer (SSL) or Transport Security Layer (TLS) that encrypts the connection between client and server and verifies the authenticity of the website, protecting the privacy and integrity of the exchanged data.  That’s it, there’s the difference.

Why you should do it

  • Security – It’s safer for you and for your users (we’ve talked about it here);
  • Trust – It doesn’t cost a fortune and the advantages in terms of security and perceived trust from your users are big, specially if you run an online store (or a bank);
  • There are ways to implement it for free using tools like Cloudflare and its Flexible SSL connection that ensures safety at least between its servers and the user.

So no disadvantages?

There are a few, but nothing serious:

  • It can add some latency to the request;
  • Caching can become tricky on high load systems (load-balancer);
  • It’s not free.

(more…)

Read more »