Symfony Access Decision Manager

Unamaous.

Unamouse.

Unamimous!

Yeah, I can’t spell.

I just hit upon a problem whereby I needed my Symfony security voter setup to always deny access even when one of my voters returned an Affirmative.

In this case I want to always deny.

By default Symfony will allow access if at least one voter returns GRANTED.

If you want to know more, check out this video I created about this very problem, and some potential solutions.

Go, No Go For Launch

Behind the scenes this week I have been extremely busy with the new site launch.

All being well, I anticipate sending out the first batch of emails today. If you’re an active site subscriber, please keep an eye on your inbox.

I still have a bunch of outstanding tasks before then, so I’m going to keep today’s update short and sweet.

Whilst I have your attention would you mind hitting reply and letting me know:

If you could see a video / course on the site that would help you right now, what would it be about?

Thanks!

This week saw three new videos added to the site:

#1 – Dependency Injection and Symfony Services (Updated for 3.3)

First up we are covering the recent changes to Symfony’s approach to Dependency Injection.

One of the recurring issues I see with many developers who are new to Symfony is in understanding how to access Services from other Services.

See, it’s fairly obvious in a Controller. There are a lot of examples about, and particularly in the docs this use case is covered a lot.

However, after a short length of time in using Symfony you will inevitably migrate from everything in your controller, to controllers making use of services.

This means creating your own services.

And these services need access to other services – whether they are services provided by the Symfony framework, or ones of your own / your team’s creation.

I often see the same mistakes being made here, so wanted to cover this in a video I can refer developers to in the future.

#2 – An Introduction to Symfony Events

I make a heck of a lot of use of Symfony’s event dispatcher.

Typically these days I try to keep my controller actions as small as possible, and one way to do this is to dispatch events when things happen during a controller action.

This is better illustrated with some code, so here goes:

    public function postAction(
        Request $request,
        EntityManagerInterface $em,
        EventDispatcher $eventDispatcher,
        CourseFactory $courseFactory
    )
    {
        $form = $this->createForm(CourseType::class, $courseFactory->create(), [
            'csrf_protection' => false,
        ]);

        $form->submit($request->request->all());

        if (!$form->isValid()) {
            return $form;
        }

        $course = $form->getData();

        $em->persist($course);
        $em->flush();

        $eventDispatcher->dispatch(
            Events::COURSE_CREATED,
            new CourseCreatedEvent($course)
        );

        $routeOptions = [
            'slug'    => $course->getSlug(),
            '_format' => $request->get('_format'),
        ];

        return $this->routeRedirectView('get_course', $routeOptions, Response::HTTP_CREATED);
    }

This is an example of a controller action from the new version of CodeReviewVideos.

This controller action allows me to create new courses, and do the majority of the common stuff inside the controller action.

I use a form to ensure the data being submitted is valid according to my business rules.

I create the course with a factory, because I no longer use Doctrine’s lifecycle events for created at / updated at.

I still save / persist the new course in the controller action. More on this in a sec.

I then dispatch an event to say, hey, a new course has been created.

At this point other interested parties (registered listeners / subscribers) can ‘hear about’ this event, and take some appropriate action.

Examples of this are writing some data to the log. Or in this case specifically, indexing the new course within Elasticsearch.

The good news is the controller action needn’t be concerned with any of that stuff. It just ensures an action is dispatched, and my concerns are nicely decoupled.

Back to why I persist in the controller still, though.

I did try moving this logic to a separate subscriber, and it did work. But I didn’t like it. It didn’t feel right, for me. Your opinion may vary, of course, and that’s cool too.

#3 – Keep Constant, and Dispatch Events from Services

There’s two parts to this video.

First, rather than rely on strings for our event names, it’s better – in my experience – to use a Constant instead.

To begin with we cover one approach to doing this. It may seem trivial, but on larger projects your sanity will be thankful 🙂

Secondly, and tying in with the video #1 above, we look at how we can dispatch events from our own Symfony services.

This second part is almost a recap of video #1, albeit a little faster, and more specific to dispatching events. The reason I cover this topic twice is because the original email I received regarding events mentioned this particular problem, which led to me creating this new short series on Symfony events in the first place.

That’s all from me for this week. Until next week, have a great weekend, and happy coding.

Chris

Docker Tutorial For Beginners (Update)

I’ve been super busy this week behind the scenes working on the new site version. Typically, every time I think I’m done (we all know we are never done :)), I hit upon something I’ve either missed, or overlooked.

There are a bunch of CSS related jobs:

Yeah… if you could just fix that margin-top, that’d be great

And React seems to have completely broken my mailing list sign up forms:

You can’t tell from a static image, but these inputs don’t allow input 🙂

And some things I only noticed when testing my user journeys:

What, no remember me?

One thing I am really happy with is the new Profile panel:

4 tabs, a lot of work 🙂

There are 29 open tickets left before I consider this next version done (again, never really done :)).

I reckon I will be happy enough to open the beta when I’m down to 20 tickets. I genuinely wish I was a 10x developer, able to blitz stuff like this out in a weekend.

I’m really looking forward to switching over though. This new site is so much nicer to work with from a development point of view. And I have a bunch of improvements from a member / visitor point of view, too 🙂

Both the front end and back end are completely separated. Both are pushed through a GitLab CI pipeline, which automates the test runs, and if all goes to plan, builds a Docker image for both. I can then deploy these using Rancher.

It’s a great setup.

As you may have noticed, Docker is currently the main course topic on the site. This is a Docker tutorial for beginners. If you’ve ever wanted to learn Docker, and prefer to see real world setups rather than simplified examples then this is the right starting point for you.

Which brings me neatly on to this weeks…

Video Update

This week saw three new videos added to the site.

All of this week’s videos fall under the same theme:

Long, and short term storage of data in Docker.

One of the most confusing aspects of switching my stack from Virtual Machines to Docker was what was happening to my data?

In Virtual Machine-land (if such a place ever existed) the location of my data was fairly obvious. It would either be on the VM itself (on the virtual hard disk), or on some attached network drive.

Things are roughly the same in Docker, but it’s not a 100% like-for-like experience. Especially not on a Mac.

#1. Docker, Without Volumes

Are volumes essential for persistent storage in Docker?

It can sometimes seem that way. A lot of Docker tutorials I followed seemed to equate persisting data with Docker Volumes.

In this video we explore persisting data within Docker containers without Volumes.

Yes, it can be done.

Yes, it works just fine.

And yes, you will lose your data if you delete the container your data belongs too 🙂

So don’t fall in to that trap. Watch this video and learn how to avoid this mistake.

#2. [Part 1] – Docker Volumes – Bind Mounts

I’m going out on a limb here, and I’m going to guess you love a good Star Trek episode as much as me.

Nothing troubles my tribbles quite like a blurt of technobabble:

The temporal surge we detected was caused by an explosion of a microscopic singularity passing through this solar system. Somehow, the energy emitted by the singularity shifted the chroniton particles in our hull into a high state of temporal polarisation.

Now the good news, when watching Star Trek, is that you really don’t need to understand any of that to gain enjoyment from the episode. The writers make sure the characters appear to understand it, and the Federation once again, save the day.

But what about technobabble we do have to understand?

Docker Bind Mounts.

Well, in this video we run our tricorder over bind mounts and figure out just what the heck these things are.

The good news?

Beyond the name they are surprisingly straightforward.

Set tachyon cannons to maximum dispersion!

#3. [Part 2] – Docker Volumes – Volumes

Here’s the unusual thing:

Docker bind mounts sounds complicated, but as we saw in the previous video, they really aren’t.

Docker volumes, on the other hand, sound quite straightforward.

But they are more complicated.

Docker’s Volumes are the future of the way we work with data in Docker.

Therefore, understanding Volumes is a very useful skill to have.

Fortunately, even though Volumes are more involved than bind mounts, by watching the previous two videos you have all the pre-requisite information required to grasp this concept.

In this video we work through a bunch of examples to ensure the fundamentals are in place. Volumes will feature heavily throughout the rest of our dealings with Docker, so be sure to understand this section before moving on.

That’s all from me for this week. Until next week, have a great weekend, and happy coding.

Chris

How can I become a Technical Evangelist?

Earlier this week I had a really interesting conversation with Thijs Feryn. You may know Thijs already, and you may have seen him / heard him speak at one of 171 different conference talks across 14 countries.

I was lucky enough to catch Thijs speak at PHP North West 2015. Incidentally, the 10th Anniversary of PHP North West occurs at the end of this month – shout up if you’re going, it would be great to meet up.

I’ve met a couple of Technical Evangelists in my time, and I have found them to be amongst the smartest people I know. And yet I’ve never though to ask them how they got that job role / title. Until now:

What I wasn’t quite expecting was the depth and quality of his response.

Thijs recorded a really interesting video / vlog answering the question:

The video itself was enough to make me sit up and take notice, but the accompanying blog post included even more depth and avenues to explore.

I shared this link out with a few devs I know earlier this week. There was a complete division that caught me off guard.

The responses I got were either:

Hey, cool, thanks for sharing, this looks interesting

or

WTF is a technical evangelist?!

Ok, so I paraphrase, but that’s the gist.

Now, I’m no expert. I can only share my view-point from the outside looking in. But here’s what I think when I hear “technical evangelist”:

A technical evangelist is a mixture of pre-sales / sales, consultant, and conference speaker.

As a technical evangelist you would be an expert in a particular field, or technology.

This typically means keeping a blog about your specialist subject, and regularly creating new content in that subject area. It helps to create very high quality / useful content as the perception that site visitors have of you both during, and after the site visit will influence who they choose when things go wrong / get complicated.

In Thijs’s case this also involves becoming a published author as a direct result of evangalising a particular tech (Varnish). Thijs goes into how this book came about and how this is different to the usual approach to writing a book.

The short version of this is best viewed from a real world problem I experienced in a previous role:

  1. My employer bought some expensive hardware
  2. I was out of my depth, so started having to learn both on the job, and in my own time
  3. Google searches led me to the same blog, over and over
  4. I went to a conference in Manchester where I met said blogger after watching him do a talk
  5. I went back to the office and told my boss about “this guy” who knew all about our problem space
  6. A few phone calls were made, and “this guy” and others from the same organisation came in to do salesy / consultancy type stuff
  7. Lots of money changed hands

I think the details here may be a little hazy as this was ~10 years ago.

Ultimately though, the company I was with at the time would never have chosen to start working with that consultant at random.

By establishing himself as a subject matter expert, backed up with conference talks and a decent blog, a lot of trust was pre-established.

From here the sell is a lot softer. In fact, I ended up as the internal advocate for this particular chap, which in turn opened the door for his company.

I can imagine, because it involves sales / money, that this whole thing sounds quite sleazy.

I would argue against this.

Sure, money changes hands. And in the context of big business, that can be big money.

But on a personal level I got to work with a subject matter expert who was both incredibly helpful, and still in my mind the very best person for the job.

Anyway, that’s why I find the whole “technical evangelist” role so fascinating. It encompasses so many of the facets of “the business of software” (or hardware) that I find so interesting.

The reason I wanted to share this with you – beyond the unexpected response from Thijs – is that there are opportunities out there that you very likely will not see advertised on the job’s boards.

To get these roles requires you to push yourself outside your comfort zone and think beyond coding.

I genuinely found this whole exchange fascinating. I’d urge you to read Thijs’s blog post, and watch his video. We spend our 37+ hours a week at work, we might as well do something super enjoyable – and being paid to evangelise a tech you personally love sounds like a brilliant role to me.

Here are some other posts on “what is a technical evangalist”, as maybe I didn’t do this justice:

Site Update

I said last week I hoped to get out some “beta” invites.

I’m almost there.

Just the 23 remaining tickets in my GitLab issues register 🙂

What’s crazy about this whole process is all I am doing at this stage is reproducing exactly what I already have. In other words, everything you see on CodeReviewVideos.com at the moment will be how the new site looks and feels in the first phase of version 2.

Kinda nuts. It’s a lot of work for the same outcome 🙂

There is method to the madness though. There are some crucial fixes to some problems of my own making in the first version of the code.

There’s also a completely new member’s area – probably the most requested feature since Site Search.

On the subject of site search, I’m now using Elasticsearch whereas the existing implementation is just MySQL fulltext (aka meh).

I’m looking forward to getting the new code “out of the door” because it means I can get back to recording a lot of new content. And I have a ton of content I want to cover.

Instructor Update

Thank you to both respondents to my request for new instructors. This made my week last week 🙂

If you’d like to create tutorials / screencasts then please do get in touch (chris @ codereviewvideos.com) and I will tell you more.

There will be a set of new pages on the new site version that explains this process further.

The short version is simply:

If you’d like to share a screencast on any subject (front end, back end, devops, open source, WordPress, Magento, other) then you are more than welcome at CodeReviewVideos.

Aside from growing your own knowledge, and sharing that knowledge with others, there is a potential for earning a monthly recurring income.

You need not be the World’s best screencaster – sharing your knowledge is the most important part.

Video Update

This week saw three new videos added to the site.

1. How can I implement Sorting in a Symfony 3 JSON API?

This video is answering a question I received regarding Sorting in Symfony (in this case, a Symfony 3 JSON API) without relying on third party bundles, such as KNP Paginator Bundle.

We cover how to sort on one field, in both Ascending, and Descending order. To this we borrow an idea from Django Rest Framework.

Then we cover how to sort on multiple fields at the same time. We cover a few ways we might restrict down what fields can / cannot be sorted on.

And we finish up by discussing whether adding this logic to your code is worth it, when more full-featured plugins (such as the aforementioned KNP Paginator) already exist.

2. Docker Images vs Docker Containers

In this video we cover the differences, and similarities between Docker Images and Docker Containers.

The tl;dr version of this would be that Docker Images are very similar to Classes in object oriented programming.

Docker Containers are as though we new up an instance of that Class.

As with almost everything in Docker-land, you can dive a lot deeper than this if needed. However, for most day-to-day tasks you likely only care that you a) have the right Docker Image, and b) can create a Docker Container from that image.

By the end of this video you will have learned about the differences between Docker Images vs Docker Containers, and have had hands-on experience with both.

3. Elixir and Phoenix with Docker Tutorial

I’m indulging myself somewhat in this short video series on Elixir, Phoenix, and Docker.

Yes, Docker is featuring heavily on the site lately 🙂

In case you aren’t aware, Elixir is a functional programming language.

Phoenix is a web framework for the Elixir programming language.

And no, I am not abandoning Symfony or PHP 🙂

I am firmly in the camp of thinking that learning a new programming language is one of the very best ways to improve your programming knowledge.

In the case of learning Elixir I have greatly improved the way I think about the structure of my code, and how each method / function can often be bettered modelled as a series of transformations of data.

Elixir has some incredibly interesting patterns and paradigms that coming from a PHP-background have been very tricky to learn.

In this short course we will create an Elixir / Phoenix stack along with Postgres for our database, and Docker to manage our infrastructure. We will then spin up a typical JSON API with all the expected interactions:

  • GET
  • POST
  • PUT
  • PATCH
  • DELETE

This sounds like a lot of work, but if you’re anything like me, you will be amazed at how quickly this implementation can be achieved.

As ever thank you very much for reading, have a great weekend, and happy coding.

Chris

How I am using Docker with Symfony, nginx, and MySQL

Behind the scenes this week I have been continuing my work on the next major iteration of the CodeReviewVideos website.

I’ve split the site into two parts:

  • A Symfony 3 powered JSON API for the back-end.
  • React / Redux / Redux Saga for the front-end

It’s a stack that I really enjoy working with, and is all stuff I’ve covered here on the site before.

Progress has gone fairly well this week. As a developer I always expect to be further ahead than I actually am. Partly this is impatience, and partly because I am still not so good at estimating 🙂

By next week’s newsletter I am hoping to be able to share access to the “beta” (for want of a better word) with existing site subscribers.

Become An Instructor

I really want to make CodeReviewVideos as useful to you as possible.

There are likely dozens of topics you’d like to see covered that either I have not yet had chance to record videos for, or do not have any experience in.

Topics like Angular 2/4, Vue, WordPress, Magento… all the things that we as developers have to work with in our real-world, day-to-day jobs.

If you have ever wanted to start recording screencasts / tutorials then this may well be the perfect opportunity to do so, and earn some extra recurring income in the process.

If you’d like to know more then please send an email to chris@codereviewvideos.com.

Video Update

This week saw three new videos added to the site.

#1. How to add a Flash Message on Successful, or Failed Login

I got asked this question:

how can I “$this->addFlash” for login? Because now its working only with registration. How can I make it work with login? Check if signing in was successful/not successful?

There is a solution built into Symfony’s security bundle (think: Login form configuration) to make this fairly easy to accomplish.

There is just one small problem: lack of documentation / example.

I’m hoping to correct that with this video. Before going too much further, you may be wondering:

What are Flash Messages?

Flash messages in Symfony are simply one time messages – notifications, by another name – that are stored in the session and are removed as soon as they have been shown once.

If still unsure, I have a video called the Beginners Guide to Symfony Flash Messages. It’s free to watch.

Symfony 3.3 comes with some improvements to the way Flash messages work.

We cover how to add a Flash Message using the success_handler and failure_handler services. The tricky part is that these two services must behave a certain way, and this video covers one approach to this problem.

I’m always open to answering questions like this, so if you have any that you feel would be best answered by video then do please send them in.

#2.  [Demo] – Docker with Symfony, nginx, and MySQL

Docker.

It’s popular.

It’s good for the CV.

It’s also complicated.

In this video we take a look at a Dockerised environment in which the latest version of Symfony 3, an nginx webserver, and a MySQL database can be “spun-up” in next to no time.

The idea here is to take a look at what’s possible, rather than me saying: Hey, this is all you need to know.

I’ve planned out the Docker series and it’s going to be a few shorter series that can be watched independently, or all together.

There are a bunch of topics in Docker that you can initially skip over. Only as and when you have a need for either a more complex setup, or want to satisfy your curiosity do you need to delve any deeper.

This is good, in my opinion, as Docker itself is both broad and deep, and if we covered all the fundamentals upfront then you may be sound asleep by the end of the first few videos.

Because seeing code is fun, here’s the docker-compose.yml file that this video covers:

# docker-compose.yml

version: '2'

services:

    db:
        image: mysql:5.7.17
        env_file:
          - ./.env
        volumes:
          - "./volumes/mysql/dev:/var/lib/mysql"
        networks:
          crv_dev_network:
            aliases:
              - mysql

    nginx:
        image: codereviewvideos/nginx.dev
        ports:
          - "81:80"
        restart: always
        volumes:
          - "./volumes/nginx/logs:/var/log/nginx/"
        volumes_from:
            - php
        networks:
          crv_dev_network:
            aliases:
              - nginx

    php:
        image: codereviewvideos/www.dev
        restart: always
        env_file:
          - ./.env
        volumes:
          - "./volumes/php/app/cache:/var/www/dev/app/cache/:rw"
          - "./volumes/php/app/logs:/var/www/dev/app/logs/:rw"
          - "./volumes/.composer:/var/www/.composer"
          - "./app:/var/www/dev"
        networks:
          crv_dev_network:
            aliases:
              - php

networks:
  crv_dev_network:
    driver: bridge

You can watch the video here, and then hit the Repo over on GitHub.

We will cover everything in this repo piece by piece, building more than just a Symfony stack in the process.

#3. Linux Permissions 101

Oh my, this sounds dull.

Yes, I hear you.

There are parts of Development that sound sexy and fun (e.g. Docker, the latest JS framework, real-time mobile apps, etc), and then there are the dry and boring sounding topics that unfortunately, you really need to know.

I realise permissions aren’t much fun.

That’s why I have compressed the essential knowledge down into a 4 minute long video.

If you have ever seen something like this:

➜  ~ ls -la Development/docker/nginx

total 24
drwxrwxr-x  4 www-data www-data 4096 Apr  3 19:43 .
drwxrwxr-x 74 chris    chris    4096 Aug 17 20:15 ..
drwxrwxr-x  2 www-data www-data 4096 Apr  3 19:37 conf.d
-rwxrwxr-x  1 www-data www-data  137 Apr 18 20:51 Dockerfile
-rwxrwxr-x  1 www-data www-data   13 Apr  3 19:42 .dockerignore
drwxrwxr-x  8 www-data www-data 4096 Aug 19 12:05 .git

And you have wondered just what the heck most of this means then this video will see you right.

To work with Docker it is essential you understand just a small amount of this output. Most every problem I have had with Docker has been related to permissions. Trust me on this, if you want to use Docker then you need to know this stuff.

And the good news is that it’s really not that bad. And it’s useful beyond working with Docker too. Win win!

Until next week, have a great weekend, and happy coding.

Chris