Is it possible to store data in one private variable of a controller (Symfony2)?
One example:
/**
* Class CatsController
*
* #Route("cats")
* #Cache(expires="+600 seconds", public=true)
* #package oTeuGato\AppBundle\Controller
*/
class CatsController extends Controller {
/**
* #var $advertisements Advertisement[]
*/
private $advertisements;
/**
* Index advertisements page
*
* #Route("", name="oTeuGato_Cats")
* #Method("GET")
* #return Response
*/
public function indexAction()
{
$this->advertisements = ....(Use a service for gets advertisements)
}
/**
* Index advertisements by page
*
* #Route("/{id}", requirements={"id" = "\d+"}, defaults={"id" = 1}, name="oTeuGato_Cats_ByPage")
* #Method("GET")
* #return Response
*/
public function indexByPageAction(){
....
}
In this example whenever someone calls the URL: cats/1 in the controller I need them to have all advertisements of the previously called method (/cats).
Is this possible?
Note:
I enabled the cache in the app.php file and app_dev.php.
Thanks for help and sorry for my English ;)
Symfony doesn't provide a mechanism for what you are describing. But any solution that would work for PHP more generally, will work for Symfony.
It depends if you want to remember advertisements for each user or for all users. If you want to remember it for each user, use sessions as Gareth Parker suggested. If you want to remember it for all users, then you would need APC user caching, memcache or another memory-based key-value store.
You may also have luck using Doctrine result cache. See http://doctrine-orm.readthedocs.org/en/latest/reference/caching.html
No, it's not. Not like that, anyway. What you want is to use sessions instead. Sessions are what you use to store variables between requests. Here are some examples
Related
Im using Open Api 3 (exactly NelmioApiDocBundle) in Symfony to document APIs and I have the following code:
* #Route("/login", name="user_login", methods={"POST"})
*
* #OA\Response(
* response=200,
* #OA\JsonContent(
* type="object",
* #OA\Property(property="code", type="number"),
* #OA\Property(property="error", type="boolean"),
* #OA\Property(property="message", type="string")
* )
* )
This works and shows me the following:
What I want to know is if there is an easier way to define these responses so I don't have to write so many lines at each endpoint.
I wish there was a way to define a JSON file as an interface and have it read from there. I've tried a thousand things but nothing works for me and I don't know how to do it and I've already given up.
Thanks a lot!
I have tried to use #Model, #Schema, modify YAML files... etc... I have read the documentation, but I have not seen any valid example for my case in this version of Open Api.
If you use models, you can put in the following
#OA\JsonContent(ref=#Model(type=LoginResponse::class))
Your response class should be something like this:
use OpenApi\Annotations as OA;
class LoginResponse
{
/** #OA\Property(type="number") */
public $code;
/** #OA\Property(type="boolean") */
public $error;
/** #OA\Property(type="string") */
public $message;
}
Make sure the properties are publicly accessible and you have symfony/property-info installed. You can also use jms/serializer, but that's a bit more work
More info at: https://symfony.com/bundles/NelmioApiDocBundle/current/index.html#use-models
I plan to add access to android & ios developers to content form Symfony 3 data. Now, access is by web browser. I've expanded logic on Controller but sharing is simple by TWIG/HTML pages.
ex.
/**
* Class DefaultController
*
* #Route("/item")
*
* #package SameBundle\Controller
*/
class DefaultController extends Controller
{
/**
* Lists all Product entities.
*
* #Route("/", name="product_index")
* #Method("GET")
*
* #Template
*/
public function indexProductAction()
{
// (...)
return ['products' => $products,];
}
It is supported by the indexProduct.html.twig page.
What do I have to add to controller/function to doing it?
To server mobile devices you will need to send them json instead of html.
So in your controller you can check if the request comes from the browser then you return html as you do it usually, and if request comes from mobile app then return json response:
return new JsonResponse($myresponse);
I am new to laravel and creating my first controller in this , i have created a file in directory app/controllers/ContactController.php and the code is
class ContactController extends BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//
echo "hieeeeeeeeeeeeeeeee";
}
/**
* Show the form for creating a new resource.
*
* #return Response
*/
public function create()
{
//
}
/**
* Store a newly created resource in storage.
*
* #return Response
*/
public function store()
{
//
}
/**
* Display the specified resource.
*
* #param int $id
* #return Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* #param int $id
* #return Response
*/
public function edit($id)
{
//
}
/**
* Update the specified resource in storage.
*
* #param int $id
* #return Response
*/
public function update($id)
{
//
}
/**
* Remove the specified resource from storage.
*
* #param int $id
* #return Response
*/
public function destroy($id)
{
//
}
}
but if i hit url http://localhost:8000/contact it is showing me the error We need a map. am i missing something???please help me.
update
i also tried to add Route::get('contact', "contact#index"); in my routes.php.
i setup an user log in and register module through git-hub and it is working perfectly if i hit url http://localhost:8000/user/login
Update
my laravel version is laravel 4
output in console is 39023 Invalid request (Unexpected EOF)
I fully agree with the things #Raviraj Chauhan already pointed out. in addition, i want to add that your file seems to have a typo which can cause this kind of issue:
Rename your controller-class to ContactController and the containing file to ContactController.php (not contactCtroller.php).
Then add a route to your routes.php-file
Route::get("contact", "ContactController#index");
Generally pay attentions to common conventions and codings-practices, since laravel heavyly depends on concepts such as Convention over Configuration.
As Lukas also pointed out it might be smart to think about switching to Laravel 5 if you are just getting startet.
Anyway, let me finish by recommending laracasts, which is how i learned using laravel. It will only take you a couple of hours to dive deeply into the laravel-universe without to much knowledge needed in advance:
Laravel 4 From Scratch
Laravel 5 Funcamentals (no need to go through L4 from Scratch before)
Yes, There is a problem with your route.
If you want to point to a single method from a controller, then you have to specify a fullControllerName#methodName convention.
Fix your route in routes.php as:
Route::get('contact', "contactController#index");
Also please follow good class naming convention while using OOP.
Controller class name shold start with capital letter.
It should contain Controller at end.
So do fix by renaming your controller class name as well as controller file name, and do:
Route::get('contact', "ContactController#index");
And by easy way, do it by command line by running:
php artisan make:controller ContactController
I got a bit stuck with multiple mappings of the same object in Doctrine. The app is build on Symfony btw, hence the slightly different annotations.
Basically I have the following objects:
Organisation: an umbrella holding attributes about an organisation
Department: a department within the organisation
User: a generic user object
Those objects are related as follows:
An organisation always has one and only one owner, which is a User
An organisation has many members, which are all User's
A department consists of many User's, but only members of the Organisation the Department is a part of are allowed
I'm a bit stuck at the third requirement... First of all, this is how my objects more or less look like atm:
/**
* #ORM\Entity
* #ORM\Table(name="organisations")
*/
class Organisation
{
// ...
/**
* #ORM\OneToOne(targetEntity="User", inversedBy="organisation")
*/
private $owner;
/**
* ORM\OneToMany(targetEntity="User", mappedBy="organisation")
*/
private $members
}
/**
* #ORM\Entity
* #ORM\Table(name="departments")
*/
class Department
{
// ...
/**
* #ORM\ManyToMany(targetEntity="User", mappedBy="departments")
*/
private $members
/**
* #ORM\ManyToOne(targetEntity="Organisation", inversedBy="departments")
*/
private $organisation;
}
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User
{
// ...
/**
* The organisation this user "owns"
*
* #ORM\OneToOne(targetEntity="Organisation", mappedBy="owner", nullable=true)
*/
private $owning_organisation;
/**
* #ORM\ManyToOne(targetEntity="Organisation", inversedBy="members")
*/
private $organisations;
/**
* #ORM\ManyToMany(targetEntity="Department", inversedBy="members")
* #ORM\JoinTable(name="users_departments")
*/
private $departments;
}
Now this basically works, if and only of in the controllers I do all the checking (something like (if( $user->isPartOfOrganisation($department-getOrganisation()) { $department->addMember($user); }).
But is there a way to restrict possible object associations on design level? So basically what I want is that if a user is added to a department, it is solely possible if the user is already part of the organisation the department is also a part of. Or should I do the check in the addMember() method of the Department object? I can imagine (but cannot find it) that there is some kind of a subset-restriction (Department::members is subset of Organisation::members).
To implements this check low-level as possible (nearest to the db) I think the only solution is a Doctrine Event Listener that in the pre-persist event check for your custom constraint. Read more about Doctrine Event System .
BTW I think you can manage this situation in a more simply manner: I suggest you to incapsulate the business logic into a service (so you can reuse it more simply) and use it in a custom validator that you will use in the form where you manage this situation.
Let me know if you need more tips to develop one of this solutions or if you found something more useful.
Hope this help
I'm looking for a way to make PHPStorm hide some methods from code completion. I've tried to annotate the DocBlocks with #access private but that does not hide them from view.
Is there any way to hide private API, short of writing/generating a stub file with a limited interface and referencing that in my project?
for example:
Lets say the library has this in it:
<?php
interface IDoABunchOfStuff
{
/**
* My library users use this
*/
public function doFoo();
/**
* My Library needs this but requires that my users don't see it.
*
* #access private
* #visibility none
* #package mylib
* #internal
*/
public function doBar();
}
class Foo extends Something implements IDoABunchOfStuff
{
/**
* does foo
*/
public function doFoo()
{
// ...
}
/**
* does bar. for internal use only
*
* #access private
* #visibility none
* #package mylib
* #internal
*/
public function _doBar()
{
// ...
}
}
And my library user is typing:
<?php
myAwesomeFunction(IDoABunchOfStuff $aFoo)
{
if($->$oFoo->[CTRL+SPACE] // invoking code completion...
Is it possible to (and if it is how do I) make it so that my user never sees _doBar?
Neither of the different annotations i've tried seem to have the desired effect.
P.S. I'm using PHPStorm 4.0.3
additional:
In this case I am implementing ArrayAccess and I don't want offsetGet, offsetSet, offsetExists and offsetUnset cluttering up my code completion window but I've had similar problems elsewhere enough to warrant asking a more generalized question.
Nope -- you cannot do such thing in current version of PhpStorm.
There is a ticket on Issue Tracker that suggests using #access tag for this purpose, but currently it is not scheduled to be implemented for any particular version: http://youtrack.jetbrains.com/issue/WI-5788
Feel free to vote/comment/etc and maybe it will be implemented sooner.