UML class diagrams basics

Most of the time we want to draw class diagrams as fast as possible but in a way, that should be understandable for any developer. I’ll show basics how to draw class diagrams and I’ll add some PHP examples.

Generalization

Classes extends parent class:

generalization

<?php 
class Animal
{
//...
}
class Cat extends Animal
{
//...
}
class Dog extends Animal
{
//...
}

Composition

When some object can’t live without another object or objects:

Composition

<?php
class Subject
{
//...
}
class Body
{
//...
}
class Receivers
{
//...
}
class Email
{
private $subject;
private $body;
private $receivers;
public function __construct()
{
$this->subject = new Subject();
$this->body = new Body();
$this->receivers = new Receivers();
}
//...
}

Aggregation

A class contains other object and when the container object dies, the object used inside do not. For example car and car engine. If you have crashed car with sports car engine, you can remove it and use it somewhere else.

Aggregation

<?php
class SportsCarEngine
{
//...
}
class Car
{
private $engine;
public function __construct($engine)
{
$this->engine = $engine;
}
//...
}
$sportsCarEngine = new SportsCarEngine();
$sportsCar = new Car($sportsCarEngine);

Interface

An interface is a specification of behaviour that a class should implement in order to be used by other classes.

interface

<?php
interface Shootable
{
public function shoot();
}
class Bow implements Shootable
{
public function shoot()
{
//...
}
}
class Shotgan implements Shootable
{
public function shoot()
{
//...
}
}

  • Juliano Santos

    Cool! Simple and objective! 🙂

    • mantasvaitkunas

      Thanks! 🙂