The Clean Architecture in php



Download 2,26 Mb.
Pdf ko'rish
bet155/179
Sana24.06.2021
Hajmi2,26 Mb.
#100337
1   ...   151   152   153   154   155   156   157   158   ...   179
Bog'liq
The-Clean-Architecture-in-PHP-Kristopher-Wilson


partials
/
flash
-
messages
.
phtml
-->
php
$flash
=
$this
->
flashMessenger
();
$flash
->
setMessageOpenFormat
(
'
data-dismiss="alert" aria-label="Close">
×

'
)
->
setMessageSeparatorString
(
'
'
)
->
setMessageCloseString
(
'
'
);
?>

=
$this
->
flashMessenger
()
->
render
(
'success'
,
[
'alert'
,
'alert-dismissible'
,
'alert-success'
]
)
?>
This is a bunch of bootstrapping to style the existing Zend helper, then using that helper to
generate the messages.
Let’s include it in the
layout.phtml
file:
<
div class
=
"container"
>
$this
->
partial
(
'application/partials/flash-messages'
)
?>

=
$this
->
content
;
?>



I'm the footer.


Now our flash message should be rendered when we create new customers.
Handling Validation Errors
On
InputFilter->isValid()
failure, we’ll want to do two things: hydrate and return a
Customer
object with the submitted data, so we can persist it to the form, and return the validation error
messages so we can show them to the user.
We’ll use the already injected
HydratorInterface
, but this time, instead of hydrating sanitized
data from the InputFilter, we’re going to hydrate the data directly posted:


Our Application in Zend Framework 2
146
public function
newAction
() {
$viewModel
=
new
ViewModel();
$customer
=
new
Customer();
if
(
$this
->
getRequest
()
->
isPost
()) {
$this
->
inputFilter
->
setData
(
$this
->
params
()
->
fromPost
());
if
(
$this
->
inputFilter
->
isValid
()) {
$this
->
hydrator
->
hydrate
(
$this
->
inputFilter
->
getValues
(),
$customer
);
$this
->
customerRepository
->
begin
()
->
persist
(
$customer
)
->
commit
();
$this
->
flashMessenger
()
->
addSuccessMessage
(
'Customer Saved'
);
$this
->
redirect
()
->
toUrl
(
'/customers'
);
}
else
{
$this
->
hydrator
->
hydrate
(
$this
->
params
()
->
fromPost
(),
$customer
);
}
}
$viewModel
->
setVariable
(
'customer'
,
$customer
);
return
$viewModel
;
}
Don’t forget to drop a
use
statement for
Zend\View\Model\ViewModel
at the top of the file.
We’ve started by declaring a new
Customer
object that gets passed along to the view. We’ve
updated our valid clause to use this customer, rather than instantiating it’s own. We’ve also
updated our
else
condition to hydrate this object with data directly from the
POST
.
Since we’re now passing off customer details to the view, we’ll need to update our view file
to use these values when generating the form, so that they’ll show the bad data when we fail
validation:


Our Application in Zend Framework 2
147
module
/
Application
/
view
/
application
/
customers
/
new
.
phtml
-->
<
div class
=
"page-header clearfix"
>
<
h2
>
New
Customer
h2
>
div
>
<
form role
=
"form"
action
=
""
method
=
"post"
>
<
div class
=
"form-group"
>
<
label
for
=
"name"
>
Name
:label
>
<
input type
=
"text"
class
=
"form-control"
name
=
"name"
id
=
"name"
placeholder
=
"Enter Name"
value
=
"$this->customer
->getName() ?>"
>
div
>
<
div class
=
"form-group"
>
<
label
for
=
"email"
>
Email
:label
>
<
input type
=
"text"
class
=
"form-control"
name
=
"email"
id
=
"email"
placeholder
=
"Enter Email"
value
=
"$this->customer
->getEmail() ?>"
>
div
>
<
button type
=
"submit"
class
=
"btn btn-primary"
>
Save
button
>
form
>
We’re now using the supplied
$customer
to set the
value
for each input. On
GET
, these values
will be empty, but on a failed
POST
, they’ll contain the user submitted data.
Now, let’s take care of showing the validation messages. First, we’ll start by making sure they
get passed off to the view in the
newAction()
:
public function
newAction
() {
$viewModel
=
new
ViewModel();
$customer
=
new
Customer();
if
(
$this
->
getRequest
()
->
isPost
()) {
// ...
if
(
$this
->
inputFilter
->
isValid
()) {
// ...
}
else
{
$this
->
hydrator
->
hydrate
(
$this
->
params
()
->
fromPost
(),
$customer
);
$viewModel
->
setVariable
(
'errors'
,
$this
->
inputFilter
->
getMessages
());
}
}
// ...
return
$viewModel
;
}


Our Application in Zend Framework 2
148
Now we can render these errors in the view file. To do that, we’re going to make a custom View
Helper to render the error messages, if present, for any given input field.
View Helpers View Helpers in Zend Framework are reusable classes that can accept data and
generate HTML. As long as they are configured properly within the service manager, ZF2 takes
care of instantiating them for you when you use them in a view.
Using View Helpers involves invoking their name from the
$this
object variable within the
view:
$this
->
helperName
(
'some data'
)
?>
We’ll create a View Helper to help us display validation messages returned to the view. Our
View Helper will live in the
module/Application/src/View/Helper
directory, and we’ll call it
ValidationErrors.php
:
namespace
Application\View\Helper;
use
Zend\View\Helper\AbstractHelper;
class
ValidationErrors
extends
AbstractHelper {
public function
__invoke
(
$element
) {
if
(
$errors
=
$this
->
getErrors
(
$element
)) {
return
''
.
implode
(
'. '
,
$errors
)
.
'
'
;
}
return
''
;
}
protected function
getErrors
(
$element
) {
if
(
!
isset
(
$this
->
getView
()
->
errors
)) {
return false
;
}
$errors
=
$this
->
getView
()
->
errors
;
if
(
isset
(
$errors
[
$element
])) {
return
$errors
[
$element
];
}
return false
;
}
}


Our Application in Zend Framework 2
149
This view helper will accept an element, which we use to lookup errors with. If we find some,
we return them rendered in pretty HTML. The errors for each element are an array (to allow for
multiple errors), so we’ll simply implode them and separate them with a period.
Next, we need to let Zend know about this view helper using it’s service locator config in
module.config.php
:
return
[
// ...
'view_helpers'
=>
[
'invokables'
=>
[
'validationErrors'
=>
'Application\View\Helper\ValidationErrors'
,
]
],
// ...
];
Finally, we can update the view file to use this new helper and display any validation error
messages for each field:
module
/
Application
/
view
/
application
/
customers
/
new
.
phtml
-->
<
div class
=
"page-header clearfix"
>
<
h2
>
New
Customer
h2
>
div
>
<
form role
=
"form"
action
=
""
method
=
"post"
>
<
div class
=
"form-group"
>
<
label
for
=
"name"
>
Name
:label
>
<
input type
=
"text"
class
=
"form-control"
name
=
"name"
id
=
"name"
placeholder
=
"Enter Name"
value
=
"$this->customer
->getName() ?>"
>
$this
->
validationErrors
(
'name'
)
?>


Email:
placeholder="Enter Email" value="

=
$this
->
customer
->
getEmail
()
?>
">

=
$this
->
validationErrors
(
'email'
)
?>

Save

If we submit the form without any data now, or with data that doesn’t meet our validation
requirements, such as an invalid email, we should get validation error messages rendered under
each field. Any data we do enter should also be preserved in the input field.


Our Application in Zend Framework 2
150
This would make a good place to commit your code to source control.
If you’re just reading, but want to see the code in action, you can checkout the tag
06-creating-customers:
git
clone
https
://
github
.
com
/
mrkrstphr
/
cleanphp
-
example
.
git
git checkout
06-
creating
-
customers
Editing Customers
Our next step is to implement the editing of existing customers. Since this code is going to be
very similar to our create customers code, we’ll use the same action and modify it slightly to
handle both new and existing Customers.
Let’s first start by refactoring our
newAction()
to be
newOrEditAction()
, and make sure it still
works before continuing. Let’s start with the
CustomersController
:
// module/Application/src/Application/Controller/CustomersController.php
// ...

Download 2,26 Mb.

Do'stlaringiz bilan baham:
1   ...   151   152   153   154   155   156   157   158   ...   179




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©hozir.org 2024
ma'muriyatiga murojaat qiling

kiriting | ro'yxatdan o'tish
    Bosh sahifa
юртда тантана
Боғда битган
Бугун юртда
Эшитганлар жилманглар
Эшитмадим деманглар
битган бодомлар
Yangiariq tumani
qitish marakazi
Raqamli texnologiyalar
ilishida muhokamadan
tasdiqqa tavsiya
tavsiya etilgan
iqtisodiyot kafedrasi
steiermarkischen landesregierung
asarlaringizni yuboring
o'zingizning asarlaringizni
Iltimos faqat
faqat o'zingizning
steierm rkischen
landesregierung fachabteilung
rkischen landesregierung
hamshira loyihasi
loyihasi mavsum
faolyatining oqibatlari
asosiy adabiyotlar
fakulteti ahborot
ahborot havfsizligi
havfsizligi kafedrasi
fanidan bo’yicha
fakulteti iqtisodiyot
boshqaruv fakulteti
chiqarishda boshqaruv
ishlab chiqarishda
iqtisodiyot fakultet
multiservis tarmoqlari
fanidan asosiy
Uzbek fanidan
mavzulari potok
asosidagi multiservis
'aliyyil a'ziym
billahil 'aliyyil
illaa billahil
quvvata illaa
falah' deganida
Kompyuter savodxonligi
bo’yicha mustaqil
'alal falah'
Hayya 'alal
'alas soloh
Hayya 'alas
mavsum boyicha


yuklab olish