Ideally, you want as few dependencies between classes as possible, since it reduces complexity. A class should only have a dependency to another class if it really needs it.
In your example, theYou state RendererPage
obviously needcontains "a set of instructions to know abouta page renderer". I imagine something like this:
renderer.renderLine(x, y, w, h, Color.Black)
renderer.renderText(a, b, Font.Helvetica, Color.Black, "bla bla...")
etc...
So it would be Page$page->renderMe($renderer)
in order to be able, since the Page needs a reference to render itrenderer.
But alternatively rendering instructions could also be expressed as a data structure rather than direct calls, eg.
[
Line(x, y, w, h, Color.Black),
Text(a, b, Font.Helvetica, Color.Black, "bla bla...")
]
In this case the actual Renderer would get this data structure from the Page and process it is not really necessary forby execute the corresponding rendering instructions. With such an approach the dependencies would be reversed - the Page does not need to know about the Renderer, but the Renderer should be provided a Page which it can then render. So the last option two: $renderer->renderPage($page);
So which is objectively best? The first approach is probably simplest to implement, while the second is much more flexible and powerful, so I guess it depends on your requirements.
If you cannot decide, or you think you might change approach in the future, you can hide the decision behind a layer of indirection, a function:
$renderer->renderPagerenderPage($page, $renderer);
(In particual The only approach I dislike the first option,will not recommend is $page->renderMe()
since it suggest a page can have only a single renderer. But what if you have a ScreenRenderer
and add a PrintRenderer
? The same page might be rendered by both.)