Making a Zend Framework 3 MVC app return a simple string - zend-framework-mvc

I have a ZF MVC app I created with composer create-project -sdev zendframework/skeleton-application my-application
I made a controller like the following.
class SomeController extends AbstractRestfulController
{
public function someAction()
{
$key = $this->params()->fromQuery('key');
if (empty($key)) {
$this->response->setStatusCode(Response::STATUS_CODE_400);
return new JsonModel([
'status'=> 'Error',
'messages'=> [
'key required'
],
]);
}
return $this->someService->getStringByKey($key));
}
}
I want it to return a content type of text/plain with a body of the results of SomeService::getStringByKey($key). Instead I get the error:
Zend\View\Renderer\PhpRenderer::render: Unable to render template "XXXXXXXXXX"; resolver could not resolve to a file
`
How do I make the controller actions just return plain strings?

Well, you are very close :)
class SomeController extends AbstractRestfulController
{
/**
* #return \Zend\Http\PhpEnvironment\Response
*/
public function someAction()
{
$string = $this->someService->getStringByKey($key));
$this->response->getHeaders()->addHeaderLine('Content-Type: text/plain');
return $this->response->setContent($string);
}
}

Related

Pass two variable to method in Laravel

i want to find post by slug also in url ..
but the comments must be found by post_id
Controller
public function post($slug,$id)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$id)->get();
return view('content.post',compact('post','comments'));
}
Route
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
public function post($slug)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
Here you go:
Get post_id from the $post itself.
public function post($slug){
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get();
...
}
You can use Route Model Binding to ensure that routes will find your model based on the provided key.
Your Post model will require that you add the following method:
public function getRouteKeyName()
{
return 'slug';
}
Then, in your routes, you can just refer the model directly, and binding will happen automatically:
public function post(App\Post $post)
{
$comments = Comment::where('post_id',$post->id)->get();
return view('content.post',compact('post','comments'));
}
This enables you to to use the following route:
Route::get('post/{post}', 'PagesController#post')->name('post.show');
Now, additionally, to ease up your reference of the comments, add them as relations to your Post model:
public function comments()
{
return $this->hasMany(Comment::class);
}
and your Comment model:
public function post()
{
return $this->belongsTo(Post::class);
}
This will allow you to shorten your controller method even more:
public function post(App\Post $post)
{
return view('content.post',compact('post'));
}
and in your Blade view do the following instead:
#foreach($post->comments as $comment)
From: {{ $comment->name }} blah blha
#endforeach
in web.php:
Route::get('post/{slug}', 'PagesController#post')->name('post.show');
in controller:
public function post($slug)
{
$post = Post::where('slug',$slug)->first();
$comments = Comment::where('post_id',$post->id)->get(); //use founded_post_id to find it's comments
return view('content.post',compact('post','comments'));
}

How to get a widget to run with multiple actions from typoscript?

In creating a new uncached widget for login/logout/registering users in the Frontend, am unable to get it to work. How can I call two different controllers from typoscript (see code below)?
Am using TYPO3 9.5. Knowing how to create one is important because I'll need that info in creating many others for various uses. I have previously created a complex login system without widget/controller/action in TYPO3.
In ext_localconf.php, there is;
\TYPO3\CMS\Extbase\Utility\ExtensionUtility::configurePlugin(
VendorName.ExtensionName,
PluginName,
[
'Frontend' => 'index',
'Account' => 'index,login,logout,register'
], [
'Account' => 'login,logout,register'
]);
Under folder structure Classes/Controller there is class VendorName\ExtensionName\Controller\AccountController which has;
class AccountController extends AbstractWidgetController {
/**
* #var array
*/
protected $supportedRequestTypes = [
Request::class,
WidgetRequest::class
];
public function initializeAction() {
}
public function indexAction() {
}
public function loginAction() {
return $this->view->assign('raw', 'Hello World');
}
public function logoutAction() {
}
public function registerAction() {
}
/**
* Handles a request. The result output is returned by altering the given response.
*
* #param \TYPO3\CMS\Extbase\Mvc\RequestInterface $request The request object
* #param \TYPO3\CMS\Extbase\Mvc\ResponseInterface $response The response, modified by this handler
*
* #return void
* #api
*/
public function processRequest(RequestInterface $request, ResponseInterface $response) {
#ActionController::processRequest($request, $response);
}
}
And in the ts file there is;
page = PAGE
page {
...
10 = USER
10 {
...
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
vendorName = VendorName
extensionName = ExtensionName
pluginName = PluginName
}
}
...
5 = USER_INT
5 {
userFunc = TYPO3\CMS\Extbase\Core\Bootstrap->run
vendorName = VendorName
extensionName = ExtensionName
pluginName = PluginName
controller = Account
action = login
}
When running this code, the PAGE ts produces the page using the Frontend controller index action which returns raw html through a fluid template. But when I add the USER_INT part, TYPO3 runs out of memory and displays a blank page.
Widgets are a type of ViewHelper used in Fluid templates. From what you describe, I think you want a plugin. Your Controller class needs to extend TYPO3\CMS\Extbase\Mvc\Controller\ActionController, not TYPO3\CMS\Fluid\ViewHelpers\Widget\Controller\AbstractWidgetController for that.

(1/1) FatalErrorException Call to a member function all() on null in laravel 5.4

4 and i have a form when submitted i want to validate its fields, what happened is when i submit the form this is what it gets
(1/1) FatalErrorException
Call to a member function all() on null
This is my code below
$validator = app('validator')->make($this->request->all(),[
'postTitle' => 'required',
'postContent' =>'required']);
In laravel 5.2 this validator works well but in laravel 5.4 it returns null
can someone help me figured this thing out?
Any help is muchly appreciated. TIA
this is my full code
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use Illuminate\Http\Request;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
protected $request;
// Intialize request instance
public function __contruct(Request $request){
$this->request = $request;
}
public function addPosts(Request $request){
//validate posts
echo "test";
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
}
Seems an issue with the method injection (in the constructor) or something.
You may try creating the request object on the local(addPosts()) function.
Please try below alternative solution.
<?php
namespace App\Repositories;
use App\Repositories\Contracts\addPostRepositoryInterface;
use Validator;
use DB;
use Session;
use Hash;
class addPostRepository implements addPostRepositoryInterface{
public function addPosts(Request $request){
//validate posts
$reqeust = new \Illuminate\Http\Request;
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
//if validation fails return error response
if($validator->fails())
return redirect()->route('get.addPost')->withErrors($validator)->withInput();
try{
}catch(\Exception $e){
return redirect()->route('get.addPost')->withErrors(["error"=>"Could not add details! Please try again."])->withInput();
}
}
public function postCreate($screen){
switch($screen){
case 'add':
return $this->addPosts($screen);
break;
}
}
//getAddPost View
public function getAddPost(){
return view('addPost');
}
// REST OF THE CODE GOES HERE...
}
Given the information you gave, I will demonstrate you how to validate a request properly in Laravel 5.4
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'postTitle' => 'required',
'postContent' =>'required',
]);
if ($validator->fails()) {
return redirect('your.view')
->withErrors($validator)
->withInput();
}
// Store the blog post...
}
This will successfully validate the request for you wherever need be. If the validation fails, you will be forwarded to your view with the according errors.
Make sure you use Validator; on top of your file.
For more information, you can read up on https://laravel.com/docs/5.4/validation

Yii2 property mapping to tablename

I use Yii2 2.0.9 basic template and I try to set up my class.
I my class I use references of other classes in my property.
/**
*
*#property Contact contact
*/
class User extends ActiveRecord {
public static function tableName() {
return "user";
}
/**
* This is want I need
*/
public function databaseMapping(){
return [
"contact" => "contact_id"
];
}
}
Is there in Yii2 a solution for my problem?
Thanks Marvin Thör
In Grails I can write this:
class User {
Contact contact
Boolean passwordExpired
static mapping = {
contact(column: 'contact_id')
passwordExpired(column: 'password_expired')
}
}
User user = new User();
user.passwordExpired = true
user.contact = new Contact();
and I want the same
You might want to use the method attributeLabels() inside your model class to define label names to show to the end user.
public function attributeLabels() {
return [
'contact_id' => 'Contact',
];
}
However, there are times like when creating a RESTful API using Yii2 that you need to return a json with fields with specific field names. For these ocasions, you can use the fields() method:
public function fields() {
return [
'contact' => 'contact_id',
];
}
This method returns the list of fields that should be returned by default by toArray(). You can check more about it HERE.
Change your labels and db column remain unchanged.
public function attributeLabels()
{
return [
'contact_id' => Yii::t('app', 'Use your name here'),
];
}

Yii2 before Validate throw PHP Warning

I used beforeValidate($insert) function and it thrown a PHP Warning when I access my post listing page:
http://localhost/yiiapp/backend/web/index.php?r=post/index
PHP Warning – yii\base\ErrorException
Missing argument 1 for app\models\Post::beforeValidate(), called in /var/www/html/yiiapp/vendor/yiisoft/yii2/base/Model.php on line 341 and defined
but when I access my create page, this Exception gone away:
http://localhost/yiiapp/backend/web/index.php?r=post/create
Actually I want to assign value one of my attribute user_id before validation in Post Model.
Here is Post Model:
class Post extends \yii\db\ActiveRecord
{
public static function tableName()
{
return 'post';
}
public function beforeValidate($insert)
{
if (parent::beforeValidate($insert)) {
$this->user_id = Yii::$app->user->id;
return true;
}
return false;
}
---
}
Why this Exception?
How I can solve this issue?
According to doc http://www.yiiframework.com/doc-2.0/yii-base-model.html#beforeValidate()-detail method beforeValidate has no attributes. Use it this way:
public function beforeValidate()
{
if (parent::beforeValidate()) {
return true;
}
return false;
}