You can clean this up significantly with the verifies()
initializer.
function init() {
verifies(
only = "show",
params = "key",
paramsTypes = "integer",
handler = "handleInvalidShowParams"
);
}
function show() {
param name="params.page" default="1";
param name="params.pageQuantity" default="10";
pins = model("pin").findByKey(
key = params.key,
returnAs = "query",
include = "user",
order = "createdat DESC",
page = params.page,
perPage = params.pageQuantity
);
}
private function handleInvalidShowParams() {
flashInsert( messages = [{ messageString="Key is required.", messageType="error" }] );
redirectTo(route="pin");
}
As you can see, we add a check to make sure that key
is present and is an integer. If either of those tests fail, the controller runs handleInvalidShowParams()
, which can do whatever you need for it to do.
This keeps the scope of show()
to what it needs to worry about, and other mechanisms in the controller can worry about parameter validation.
Update
Take a look at the 2nd line, which I've added in:
addRoute(name="pinShow", pattern="pin/show/[key]", controller="pin", action="show");
addRoute(name="pinShow", pattern="pin/show", controller="pin", action="show");
addRoute(name="pinEdit", pattern="pin/edit/[key]", controller="pin", action="edit");
addRoute(name="pinDelete", pattern="pin/delete/[key]", controller="pin", action="delete");
addRoute(name="pinUpdate", pattern="pin/update", controller="pin", action="update");
addRoute(name="pinNew", pattern="pin/new", controller="pin", action="new");
addRoute(name="pinCreate", pattern="pin/create", controller="pin", action="create");
addRoute(name="pinWanted", pattern="pin/wanted", controller="pin", action="wanted");
addRoute(name="pin", pattern="pin", controller="pin", action="index");
I believe that will catch the /pin/show
pattern without a key.
As extra credit, I might suggest that you take a look at the ColdRoute plugin and the accompanying screencast series because it makes a lot of this stuff much more trivial.