Nette Documentation Preview

syntax
SmartObject: PHP Object Enhancements
************************************

<div class=perex>

SmartObject extends PHP's object capabilities with a few syntactic candies. Do you like candy? Read and learn

- why it is good to use `Nette\SmartObject`
- what are *properties*
- how to trigger events

</div>

In this chapter, we are focusing on `Nette\SmartObject`, a trait  which extends PHP's object capabilities. This trait is used by almost all classes in the Nette Framework. At the same time, it is transparent enough to be used in your classes. Let's try to say why you should do it.

Trait `Nette\SmartObject` is a simplified successor to the obsolete class `Nette\Object` from Nette 2.x.

Installation:

```shell
composer require nette/utils
```


Strict Classes
==============

PHP gives huge freedom to developers, which makes it a perfect language for making mistakes. But you can stop this bad behavior and start writing applications without hardly discoverable mistakes. Do you wonder how? It's really simple -- you just need to have stricter rules.

Can you find an error in this example?

```php
class Circle
{
	public $radius = 0.0;

	public function getArea()
	{
		return $this->radius * $this->radius * M_PI;
	}
}

$circle = new Circle;
$circle->raduis = 10;
echo $circle->getArea(); // 10² * π ≈ 314
```

On the first look, it seems that code will print out 314; but it returns 0. How is this even possible? Accidentally, `$circle->radius` was mistyped to `raduis`. Just a small typo, which will give you a hard time correcting it because PHP does not say a thing when something is wrong. Not even a Warning or Notice error message. Because PHP does not think it is an error.

The mentioned mistake could be corrected immediately, if class `Circle` would use `Nette\SmartObject`:

```php
class Circle
{
	use Nette\SmartObject;
}
```

Whereas the former code executed successfully (although it contained an error), the latter did not:

[* debugger-circle.webp .{url:-} *]

Trait `Nette\SmartObject` made `Circle` more strict and threw an exception when you tried to access an undeclared property. And [Tracy |tracy:] displayed an error message about it. Line of code with a fatal typo is now highlighted and the error message has a meaningful description: *Cannot write to an undeclared property Circle::$raduis, did you mean $radius?*. The programmer can now fix the mistake he might have otherwise missed and which could be a real pain to find later.

One of many remarkable abilities of `Nette\SmartObject` is throwing exceptions when accessing undeclared members.

```php
$circle = new Circle;
echo $circle->undeclared; // throws Nette\MemberAccessException
$circle->undeclared = 1; // throws Nette\MemberAccessException
$circle->unknownMethod(); // throws Nette\MemberAccessException
```

But it has much more to offer!

.[note]
Use `SmartObject` only for base classes that do not inherit from anyone, the functionality will be forwarded in all its descendants.


Properties, Getters and Setters
===============================

*(For more experienced programmers)*

In modern object-oriented languages (eg C#, Python, Ruby, JavaScript), the term *property* refers to [special members|https://en.wikipedia.org/wiki/Property_(programming)] of a classes, which look like variables but are represented by methods. When reading or assigning values to those "variables", methods are called instead (so-called getters and setters). It is a really useful feature, which allows us to control access to these variables. Using this we can validate inputs or postpone the computation of values of these variables to the time when it is actually accessed.

Any class that uses `Nette\SmartObject` acquires the ability to imitate properties. How to do it?

- Add an annotation to the class in the form `@property <type> $xyz`
- Create a getter named `getXyz()` or `isXyz()`, a setter named `setXyz()`
- Getter and setter must be *public* or *protected* and both are optional, so there can be *read-only* or *write-only* properties

We will make use of properties in the class Circle to make sure the variable `$radius` contains only non-negative numbers. We will replace `public $ radius` with the property:

```php
/**
 * @property float $radius
 * @property-read bool $visible
 */
class Circle
{
	use Nette\SmartObject;

	private $radius = 0.0; // not public anymore!

	// getter for property $radius
	protected function getRadius()
	{
		return $this->radius;
	}

	// setter for property $radius
	protected function setRadius($radius)
	{
		// sanitizing value before saving it
		$this->radius = max(0.0, (float) $radius);
	}

	// getter for property $visible
	protected function isVisible()
	{
		return $this->radius > 0;
	}
}

$circle = new Circle;
$circle->radius = 10;  // calls setRadius(10)
echo $circle->radius;  // calls getRadius()
echo $circle->visible; // calls isVisible()
```

Properties are mostly a syntactic sugar to beautify the code and make programmer's life easier. You do not have to use them, if you don't want to.


Events
======

*(For more experienced programmers)*

Now we are going to create functions, which will be called when radius changes. Let's call it `change` event and those functions event handlers:

```php
class Circle
{
	use Nette\SmartObject;

	/** @var array */
	public $onChange = [];

	public function setRadius($radius)
	{
		// it calls callbacks in $onChange with parameters $this, $radius
		$this->onChange($this, $radius);

		$this->radius = max(0.0, (float) $radius);
	}
}

$circle = new Circle;

// adding an event handler
$circle->onChange[] = function (Circle $circle, $newValue) {
	echo 'there was a change!';
};

$circle->setRadius(10);
```

In the code of the `setRadius` method, you see another syntactic sugar - instead of iteration on `$onChange` array and calling each callbacks, you just have to write simple `onChange(...)` and specify the parameters that are passed to each callback.

So SmartObject creates a fictitious `onChange()` method named after  the `$onChange` array. A convention of `on` + word is required.


Static Classes
==============

You can mark static classes, that is, classes that are not intended to be instantiated, with `Nette\StaticClass` trait:

```php
class Strings
{
	use Nette\StaticClass;
}
```

When trying to instantiate it, an `LogicException` exception is thrown with the information that the specified class is static.

SmartObject: PHP Object Enhancements

SmartObject extends PHP's object capabilities with a few syntactic candies. Do you like candy? Read and learn

  • why it is good to use Nette\SmartObject
  • what are properties
  • how to trigger events

In this chapter, we are focusing on Nette\SmartObject, a trait which extends PHP's object capabilities. This trait is used by almost all classes in the Nette Framework. At the same time, it is transparent enough to be used in your classes. Let's try to say why you should do it.

Trait Nette\SmartObject is a simplified successor to the obsolete class Nette\Object from Nette 2.x.

Installation:

composer require nette/utils

Strict Classes

PHP gives huge freedom to developers, which makes it a perfect language for making mistakes. But you can stop this bad behavior and start writing applications without hardly discoverable mistakes. Do you wonder how? It's really simple – you just need to have stricter rules.

Can you find an error in this example?

class Circle
{
	public $radius = 0.0;

	public function getArea()
	{
		return $this->radius * $this->radius * M_PI;
	}
}

$circle = new Circle;
$circle->raduis = 10;
echo $circle->getArea(); // 10² * π ≈ 314

On the first look, it seems that code will print out 314; but it returns 0. How is this even possible? Accidentally, $circle->radius was mistyped to raduis. Just a small typo, which will give you a hard time correcting it because PHP does not say a thing when something is wrong. Not even a Warning or Notice error message. Because PHP does not think it is an error.

The mentioned mistake could be corrected immediately, if class Circle would use Nette\SmartObject:

class Circle
{
	use Nette\SmartObject;
}

Whereas the former code executed successfully (although it contained an error), the latter did not:

Trait Nette\SmartObject made Circle more strict and threw an exception when you tried to access an undeclared property. And Tracy displayed an error message about it. Line of code with a fatal typo is now highlighted and the error message has a meaningful description: Cannot write to an undeclared property Circle::$raduis, did you mean $radius?. The programmer can now fix the mistake he might have otherwise missed and which could be a real pain to find later.

One of many remarkable abilities of Nette\SmartObject is throwing exceptions when accessing undeclared members.

$circle = new Circle;
echo $circle->undeclared; // throws Nette\MemberAccessException
$circle->undeclared = 1; // throws Nette\MemberAccessException
$circle->unknownMethod(); // throws Nette\MemberAccessException

But it has much more to offer!

Use SmartObject only for base classes that do not inherit from anyone, the functionality will be forwarded in all its descendants.

Properties, Getters and Setters

(For more experienced programmers)

In modern object-oriented languages (eg C#, Python, Ruby, JavaScript), the term property refers to special members of a classes, which look like variables but are represented by methods. When reading or assigning values to those „variables“, methods are called instead (so-called getters and setters). It is a really useful feature, which allows us to control access to these variables. Using this we can validate inputs or postpone the computation of values of these variables to the time when it is actually accessed.

Any class that uses Nette\SmartObject acquires the ability to imitate properties. How to do it?

  • Add an annotation to the class in the form @property <type> $xyz
  • Create a getter named getXyz() or isXyz(), a setter named setXyz()
  • Getter and setter must be public or protected and both are optional, so there can be read-only or write-only properties

We will make use of properties in the class Circle to make sure the variable $radius contains only non-negative numbers. We will replace public $ radius with the property:

/**
 * @property float $radius
 * @property-read bool $visible
 */
class Circle
{
	use Nette\SmartObject;

	private $radius = 0.0; // not public anymore!

	// getter for property $radius
	protected function getRadius()
	{
		return $this->radius;
	}

	// setter for property $radius
	protected function setRadius($radius)
	{
		// sanitizing value before saving it
		$this->radius = max(0.0, (float) $radius);
	}

	// getter for property $visible
	protected function isVisible()
	{
		return $this->radius > 0;
	}
}

$circle = new Circle;
$circle->radius = 10;  // calls setRadius(10)
echo $circle->radius;  // calls getRadius()
echo $circle->visible; // calls isVisible()

Properties are mostly a syntactic sugar to beautify the code and make programmer's life easier. You do not have to use them, if you don't want to.

Events

(For more experienced programmers)

Now we are going to create functions, which will be called when radius changes. Let's call it change event and those functions event handlers:

class Circle
{
	use Nette\SmartObject;

	/** @var array */
	public $onChange = [];

	public function setRadius($radius)
	{
		// it calls callbacks in $onChange with parameters $this, $radius
		$this->onChange($this, $radius);

		$this->radius = max(0.0, (float) $radius);
	}
}

$circle = new Circle;

// adding an event handler
$circle->onChange[] = function (Circle $circle, $newValue) {
	echo 'there was a change!';
};

$circle->setRadius(10);

In the code of the setRadius method, you see another syntactic sugar – instead of iteration on $onChange array and calling each callbacks, you just have to write simple onChange(...) and specify the parameters that are passed to each callback.

So SmartObject creates a fictitious onChange() method named after the $onChange array. A convention of on + word is required.

Static Classes

You can mark static classes, that is, classes that are not intended to be instantiated, with Nette\StaticClass trait:

class Strings
{
	use Nette\StaticClass;
}

When trying to instantiate it, an LogicException exception is thrown with the information that the specified class is static.