수업소개
abstract는 클래스의 메소드를 하위 클래스가 반드시 오버라이드 하도록 하는 것입니다. 이것을 통해서 부모 클래스의 일부 기능을 하위 클래스가 구현하도록 강제할 수 있습니다.
이 수업에서는 디자인 패턴이 무엇인가를 설명합니다. 그 중에서 템플릿 메소드 패턴을 통해서 추상 클래스가 사용되는 구체적인 사례를 살펴봅니다.
수업
소개
형식
<?php
abstract class ParentClass
{
public function a()
{
echo 'a';
}
public abstract function b();
}
class ChildClass extends ParentClass
{
public function b()
{
}
}
사례 : 템플릿 메소드 패턴
템플릿 메소드 패턴 구현
<?php
abstract class AbstractPageTemplate
{
protected final function template()
{
$result = $this->header();
$result .= $this->article();
$result .= $this->footer();
return $result;
}
protected abstract function header();
protected abstract function article();
protected abstract function footer();
public function render()
{
return $this->template();
}
}
class TextPage extends AbstractPageTemplate
{
protected function header()
{
return "PHP\n";
}
protected function article()
{
return "PHP: Hypertext Preprocessor\n";
}
protected function footer()
{
return "website is php.net\n";
}
}
class HtmlPage extends AbstractPageTemplate
{
protected function header()
{
return "<header>PHP</header>\n";
}
protected function article()
{
return "<article>PHP: Hypertext Preprocessor</article>\n";
}
protected function footer()
{
return "<footer>website is php.net</footer>\n";
}
public function render()
{
$result = '<html>';
$result .= $this->template();
return $result.'</html>';
}
}
echo '<h1>text</h1>';
$text = new TextPage();
echo $text->render();
echo '<h1>html</h1>';
$html = new HtmlPage();
echo $html->render();

