The Clean Code Talks - Don't Look For Things!

By: GoogleTechTalks

1127   31   207963

Uploaded on 11/08/2008

Google Tech Talks
November 6, 2008

ABSTRACT

Clean Code Talk Series
Topic: Don't Look For Things!

Speaker: Misko Hevery

Comments (15):

By anonymous    2017-09-23

https://www.youtube.com/watch?v=RlfLCWKxHJ0&feature=youtu.be

Original Thread

By anonymous    2017-09-20

Instead of that dreadful abomination, you should learn how to utilize spl_autoload_register():

spl_autoload_register( function( $classname ){

    $filename = 'inc/classes/' . $classname . '.class.php';

    if ( !file_exists( $filename) ){
        throw new Exception("Could not load class '$classname'.". 
                            "File '$filename' was not found !");
    }

    require $filename;

});

And you should register the autoloader in your index.php or bootstrap.php file, and do it only once per loader (this ability lets you define multiple loaders, but that's used, when you have third party library, which has own autoloader .. like in case of SwiftMailer).

P.S. please learn to use prepared statements with MySQLi or PDO.

Update

Since you are just now learning OOP, here are few things, which you might find useful:

Lectures:

Books:

Original Thread

By inglor    2017-09-21

I'll try to elaborate, global _app_ state is different from global state "in the wild".

The internet is "global state" but you wouldn't call any code that makes HTTP requests global state because the "globality" is isolated inside your app.

Global can mean several things, my point was only that "globality" inside your app can (and should) be very constrainted while acknowledging some things are indeed global from your app's point of view. A good example of this is having a global "db" object vs. a DB instance passed to places.

This is more about whether or not your code should care about where it gets data or not. I think this (now classic) talk is a nice explanation about why your components should not "look for things" in the global but instead should be explicit about dependencies any why it's easier to reason about: https://www.youtube.com/watch?v=RlfLCWKxHJ0

Original Thread

By anonymous    2017-09-20

Your question is:

Inside a class, can I create instances of other classes?

Well, theoretical and technical, you can easily receive the answer "yes". But the real answer is... "no". Because, if you do it:

  • you are tightly coupling the class in which the instances are created (Car) to the classes from which the instances are created (Engine, Wheels, FuelTank). This way, a car will always must have a fuel tank, even though there could be implemented an electrical power only solution.
  • the car will not only have the responsibility to go on a road, but to create its car parts by itself, too. And this is somehow... "Transformers"-like.

But, if you want to correctly learn and apply OOP, then these two situations are not a "permitted" option. It's the same as: in a normal swimming competition you could use a pair of fins, but you would be desqualified.

That said, the only viable alternative to tight coupling is the loose coupling: the car parts are injected, e.g. passed, e.g. plugged into the car. In OOP, this process has the name dependency injection (DI). The car parts - the dependencies - can then be easily changed, or removed. So, the fuel tank can then be completely removed, because the car will be driven only with electrical power. The car itself has now the single responsibility of going on a road. And, even if it still depends on its parts - as it should, the car is not anymore concerned with the process of car parts creation: it just receives them - as it should.

I just realised, that I'd use another conceptual scheme: an Engine should not be a CarPart. Only the fact that it's plugged into a car makes it a car part. The same goes for the Wheels and FuelTank. In short, I'd define them in other way:

class Engine {...}
class Wheels {...}
class FuelTank {...}

class CarEngine extends Engine {...}
class CarWheels extends Wheels {...}
class CarFuelTank extends FuelTank {...}

So, the loose coupling will be applied like this:

class Car{

    Car(instance of CarEngine, instance of CarWheels, instance of CarFuelTank){
        //...
    }

}

or, even better, in analogy with your code version:

class Car {

    Car(instance of Engine, instance of Wheels, instance of FuelTank){
        //...
    }

}

Here are two wonderful resources for a better understanding of the principles presented here:

Good luck with your projects!


EDIT 1:

@Ryan The Leach kindly and rightly proposed me to also present you the notion/concept of factory. I'll try to do it in a principle manner.

The car needs an engine to be able to function. But who could produce this car part? Well: an engine factory. More precisely a car engine factory.

In terms of OOP, a factory is a specialized class having a single responsibility: the creation of instances of other classes (sounds familiar?). The created instances are then used somewhere else, according with their usefulness. Now, when a factory creates an object, or more objects of different class types, it may need to gather/produce other resources too, in order to prepare the creation of the final "product(s)".

So, an engine factory would first need to gather/produce a lot of engine pieces before assembling/creating the final engine. The same applies to a car factory: it needs to receive an engine from the engine factory, wheels from the wheels factory and a fuel tank from the fuel tanks factory. Then it produces the final cars.

In OOP, there are three types of factories, e.g of so called factory patterns:

  • The simple factory
  • The factory method and
  • The abstract factory.

I'll not present them here personally, but I'll try to direct you to some (very) good web resources, easy to follow and understand:

P.S:

The first two are my favorites... although I didn't watched them yet :-) Yes, silly, isn't it? Because they are relative new uploads I didn't knew that they exist. BUT: I followed all the other streams of the author and, in three words: I was impressed. Nota bene: the author explains all the patterns presented in the book "Head First Design Patterns".

Original Thread

By anonymous    2017-09-20

First question:

The first problem happens because you are loading and rendering the view files IN the action context/scope of the controller. That's why your url in the point 3. is "incorrect", e.g. site-test/tasks/page/tasks, e.g '///`. So, other said, because you are actually seeing the rendered html content from inside the controller folder, where it was the view file rendered.

In order to resolve this you have to options:

Option 1) Use absolute paths in all the anchors in your view/template files, like for example:

<a href="http://site-test/tasks/">tasks</a>
<a href="http://site-test/tasks/page/2">next page</a>

Here you can of course use a variable in your view/template files instead, like:

<a href="<?php echo $host; ?>/tasks/">tasks</a>
<a href="<?php echo $host; ?>/tasks/page/2">next page</a>

I showed you just pure php code, but you can use syntaxes provided by a diversity of template engines, if you decide to use one, one then PHP engine.

Option 2) Use relative paths in all the anchors in your view/template files, like for example:

<a href="/tasks/">tasks</a>
<a href="/tasks/page/2">next page</a>

The key is of course the slash (/) at the beginning of each anchor's href attribute. It ensures that all the links are "joined" to the host http://site-test of your MVC website.

Personally I use the second option in my own MVC framework and it works smooth and is... pretty.

Second question:

When url is: site-test or site-test/tasks all files loading from root_directory/images or root_directory/css, when url is: site-test/tasks/page/2 he tries to find these files in root_directory/tasks/page/images

Well, here is the need of a discussion:

When url is site-test, then the default action of the default controller is called, e.g. Controller_add_task::action_index(). You didn't show the code for that controller, so I can't say nothing about from where and how are the asset files (css, images, js) loaded in the views.

Same goes for the url site-test/tasks/page/...: you showed the code for the controller, but I can't say nothing about how and where are the asset files (css, images, js) loaded in the views. Are the asset paths loaded from inside the Controller (parent class) methods? Are they written - as normal - in the view/template files (using <script src=...>, <link href=...>, <img src=...>)? Are they loaded from inside the View::generate?

In principle, they can be passed to the view/template files as variables, or they can be written - as normal - in the view/template files.

The context/scope theory of the first question applies here too. And the key here is the same as in the first question: the asset paths should be passed/written as absolute paths or relative paths as shown above in the options 1) and 2).

Recommendations:

Note: Seeing that you want to learn clean MVC, I thought you would allow me to give you some tips:

*) Don't use any static classes/functions, singletons or so called service locators. Trust me, you don't need them at all if you are writing a clean, good testable MVC.

*) Use a dependency injection container like Auryn, which you will implement only on the entry point of your app, e.g. bootstrap.php or index.php. The next point tells you why.

*) Inject your dependencies, don't create them in the places where they are needed. So not like this:

function __construct()
    {
        $this->model = new Model_tasks();
        $this->view = new View();
    }

but like this:

function __construct(Model_tasks $model, View $view)
    {
        $this->model = $model;
        $this->view = $view;
    }

Read:

*) Use namespaces! Read PSR-4: Autoloader (yes, it's correct).

*) Read all the first 8 recommendations in PHP Standards Recommendations. They are very important if you want to correctly learn how to develop a PHP MVC.

*) Learn the five SOLID principles in OOP (just search for "solid principles" in web).

*) Use a corresponding view class for each controller class (1:1). For example: if you have TasksController, then also create a class TasksView. And what you are using there as view files - tasks_view.php, template_view.php, etc - are actually template files. And you should implement a Template class, which is to be injected in the corresponding view class. The template class is actually responsible for rendering/loading the template files. The view class should be responsible to output the rendered content (or to pass it to a Response class to be outputed).

Read: Understanding MVC Views in PHP

*) Don't use names like Controller_tasks for the class names. Use the syntax like this - I forgot the name: TasksController, TasksModel, TasksView.

*) Don't use names like action_index for the class methods or members. Use the camelCase syntax. And don't use action in the controller methods, because you already know that. So write the methods just like this: index(), page(), listBooks. If you use ajax you can name them like ajaxGetUsers(), etc. Just make sure that your routing system make the correct syntax-mapping between the controller/action names in url and the actual controller/action names.

Resources:

Good luck.

Original Thread

By anonymous    2017-09-23

Let's look at the real life example. Let's say you have a car. Car needs an engine.

class Car
{
    private $engine;

    public function __construct()
    {
        $this->engine = new V6Engine();
    }
}

The car has a dependency on the engine. In this case, the car itself needs to construct a new engine! Does it make sense? Well.. NO! Also, the car is coupled to the specific version of the engine.

This makes more sense. Someone else needs to provide the car engine. It could be some engine supplier, engine factory... It is not car's job to create engine!

class Car
{
    private $engine;

    public function __construct(Engine $engine)
    {
        $this->engine = new $engine;
    }
}


interface Engine
{
    public function start();
}

class V6Engine implements Engine
{
    public function start()
    {
        echo "vrooom, vrooom V6 cool noise"
    }
}

Also, you could easily swap the engine, you are not coupled to the specific engine. That new engine only needs to be able to start.

Martin Fowler has written a very good article about the inversion of control and dependency injection.

https://martinfowler.com/articles/injection.html

Please read it - because he will explain the DI much better than I can do :)))

Also, there is very good video by the Miško Hevery "The Clean Code Talks - Don't Look For Things!". You will be much clever after watching it :)

https://www.youtube.com/watch?v=RlfLCWKxHJ0

Original Thread

By anonymous    2017-09-23

You are doing quite a lot things wrong there.

Don't wrap PDO class

PDO already is a DB acces abstraction. You do not need to abstract the abstraction. You are also doing the prepared statements wrong in your code, which makes your code vulnerable to SQL injections. Please check the linked manual article and pay specific attention to use of bindParam() and bindValue() methods. You could also watch this video (it's uses mysqli in the examples, but the core mechanic is the same), which should explain where to injection vulnerability actually comes from.

Use dependency injection

Your current code relies on the global state. Instead you should inject the PDO instance as a dependency in your Settings service.

In practice it would looks something like this:

class Setting {
    privare $connection;

    public function __construct(PDO $connection) {
        $this->connection = $connection;
    }

    public function options($option_name) {
        // codes here
    }
};

The idea basically is:

$db = new PDO;
$foo = new Foo($db);
$bar = new Bar($db);

This way the both Foo and Bar instance have the same DB connection.

Watching this lecture would be highly recommended.

Original Thread

By anonymous    2017-10-22

Here are some very good resources to study. They will give you the answer to the question "How can I make it right?". [The Clean Code Talks - Don't Look For Things!](https://www.youtube.com/watch?v=RlfLCWKxHJ0), [PHPNW15: James Mallison - Dependency Injection and Dependency Inversion in PHP](https://www.youtube.com/watch?v=Ojsn11XY0X8&feature=youtu.be), [Managing Class Dependencies: ..., Part 1](https://www.sitepoint.com/managing-class-dependencies-1/), [Managing Class Dependencies: ..., Part 2](https://www.sitepoint.com/managing-class-dependencies-2/),

Original Thread

By anonymous    2017-10-30

Ishegg is right. Here are two very good resources which sustain and explain what he says: [The Clean Code Talks - Don't Look For Things!](https://www.youtube.com/watch?v=RlfLCWKxHJ0) and [James Mallison - Dependency Injection and Dependency Inversion in PHP](https://www.youtube.com/watch?v=Ojsn11XY0X8&feature=youtu.be).

Original Thread

By anonymous    2017-10-30

A good answer! ;-) Just a note though: the "OK" version I would directly entitle as "BAD" (regarding config array and tight coupling): [The Clean Code Talks - Don't Look For Things!](https://www.youtube.com/watch?v=RlfLCWKxHJ0) and [James Mallison - Dependency Injection and Dependency Inversion in PHP](https://www.youtube.com/watch?v=Ojsn11XY0X8&feature=youtu.be).

Original Thread

By anonymous    2017-10-30

See: [YouTube: Clean Code Talks](http://www.youtube.com/watch?v=RlfLCWKxHJ0).

Original Thread

By anonymous    2017-11-06

I am learning the popular MVC and trying to implement it in PHP. I am designing a framework with a pure OOP fashion (though I am not expert in PHP's OOP ability. I only have moderate knowledge about it). An example implementation of this framework as shown in the following figure. enter image description here

In this framework I added a Data Access Layer, DAL, (a class to deal with the connection, executing query and transport to and from the database) to abstract the physical database from the rest of the system to easy change of the data source. If a system is only bind to one database of one particular type, this layer is expected to presented in the system using only one object with one connection to the database. And this object will be a dependency for all the Data Mapper objects (i.e., User mapper, Product Mapper).

I am looking for your comments on where to initiate the DAL object in the system. I can create the object in the front controller (index.php) and transport all the way to Data Mapper objects. But it is an anti-pattern according to Here and Here. Even for the same reason, we cannot initiate the DAL object within the factories (Factories can be separated in multiple classes for handling complexities as per Clean code approach ). I cannot use Singleton as that is also going to create lots of problem according to this. So, in your opinion, what is the best practice and place where I can initiate this object and pass it to Data Mapper objects?

N.B.: I disregard the View Logic here as my concern do not have any relation with Views.

Original Thread

Recommended Books

    Popular Videos 323

    Submit Your Video

    If you have some great dev videos to share, please fill out this form.