table object and its associations in non related controller - cakephp-3.7

I have one controller say dashboardContoller, in that I want to fetch data from table class, but i'm not able to get table class object in $this object on that controller. I have observed that event manager is containing table object in old version of cake php2.7.
Currently I'm upgrading cake php 2.7 to 3.7 and in that I'm not able to fetch table from $this object.
Simply below code is not working in upgraded version
namespace app\Controller;
use App\Controller\AppController;
use Cake\Log\Log;
use App\Model\Entity\Group;
use App\Model\Entity\User;
use Cake\ORM\TableRegistry;
class DashboardController extends AppController {
public $uses = array('Users', 'Module', 'ModuleAccreditation', 'Reminder', 'BusinessRelationship', 'Document', 'Membership', 'Invoice');
protected function _dashboardData() {
$membershipStatusCount = $this->User->Membership->MembershipStatus->getCounts();
$moduleAccreditationStatusCount = $this->ModuleAccreditation->ModuleAccreditationStatus->getCounts();
}
}

Related

How to add model to PredictionEnginePool in middleware (ML.NET)?

I'm using ML.NET in an ASP.NET Core application, and I am using the following code in Startup:
var builder = services.AddPredictionEnginePool<Foo, Bar>();
if (File.Exists("model.zip"))
{
builder.FromFile(String.Empty, "model.zip", true);
}
If model.zip doesn't exist, I create it later in the middleware. How do I add it to the PredictionEnginePool that is injected?
There are no options to load a model via PredictionEnginePool, and instantiating or injecting a PredictionEnginePoolBuilder isn't an option as it requires IServiceCollection (so must be configured during Startup.ConfigureServices).
The only option I can see at the moment is to set a flag if the file doesn't exist at startup, and then restart the service after model.zip is created in the middleware later on (using IApplicationLifetime.StopApplication), but I really don't like this as an option.
PredictionEnginePool is designed in such a way that you can write your own ModelLoader implementation. Out of the box, Microsoft.Extensions.ML has 2 loaders, File and Uri. When those don't meet your needs, you can drop down and write your own.
See https://github.com/dotnet/machinelearning-samples/pull/560 which changes one of the dotnet/machine-learning samples to use an "in-memory" model loader, it doesn't get the model from a file or a Uri. You can follow the same pattern and write whatever code you need to get your model.
public class InMemoryModelLoader : ModelLoader
{
private readonly ITransformer _model;
public InMemoryModelLoader(ITransformer model)
{
_model = model;
}
public override ITransformer GetModel() => _model;
public override IChangeToken GetReloadToken() =>
// This IChangeToken will never notify a change.
new CancellationChangeToken(CancellationToken.None);
}
And then in Startup.cs
services.AddPredictionEnginePool<ImageInputData, ImageLabelPredictions>();
services.AddOptions<PredictionEnginePoolOptions<ImageInputData, ImageLabelPredictions>>()
.Configure(options =>
{
options.ModelLoader = new InMemoryModelLoader(_mlnetModel);
});

How to inject app.context into Loopback 4 controller

I cannot find any suitable example on how to inject an app.context object into a Loopback 4 controller being in a separate file
This inline example from the documentation works fine
import {inject} from '#loopback/context';
import {Application} from '#loopback/core';
const app = new Application();
app.bind('defaultName').to('John');
export class HelloController {
constructor(#inject('defaultName') private name: string) {}
greet(name?: string) {
return `Hello ${name || this.name}`;
}
}
but I cannot find a way to obtain the same having my controller in a separate file.
I am trying to do something like this:
export class PingController {
constructor(#inject(app.name) private name: string)
app.name being a simple binding in my app-context.
Solution was quite simple.
Since all context values on app level is available throughout the application, no reference to app is required.
I just needed to replace (app.name) with ('name') in the constructor injection.

fetching from Coredata in ios app widget extension in ios 10

Im trying to fetch entities from my coredata database of my main app and display them in my apps widget Extention. However the fetch always returns an empty results from my database. Can ayone help me out. Swift 3, ios 10.
I solved it. After creating the App Group, I created a subclass of NSPersistentContainer and override the class method defaultDirectory() to return the shared app group directory. Also override the init(name: String, managedObjectModel model: NSManagedObjectModel). Then in the coredata stack you replace the boilerplate persistentcontainer code with a new instance of the PersistentContainer class created.
import UIKit
import CoreData
class PersistentContainer: NSPersistentContainer{
override class func defaultDirectoryURL() -> URL{
return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.bundleId.SomeApp")!
}
override init(name: String, managedObjectModel model: NSManagedObjectModel) {
super.init(name: name, managedObjectModel: model)
}
}
Then in the CoreDataStack Code *wherever that maybe, either in the Appdelegate or or its own file. Mine was in its own file named CoredataStack
static var persistentContainer:PersistentContainer = {
let container = PersistentContainer(name: "SomeApp", managedObjectModel: CoreDataStack.managedObjectModel)
container.loadPersistentStores(completionHandler: { (storeDescription:NSPersistentStoreDescription, error:Error?) in
if let error = error as NSError?{
fatalError("UnResolved error \(error), \(error.userInfo)")
}
})
return container
}()
Hope this helps out
Today Extension runs in a different process from its containing app, thus do not share sandbox, UserDefaults, or database tabled. That is why you get an empty set when trying to fetch data saved in container, from the widget.
If you want the containing app and the widget to share data, you should add to your app the capability "App Group" via the iOS developer portal and give it a shared group identifier string.
Next, when you instantiate the FileManager object for the database (or UserDefaults), you must use initWithSuiteName method to, passing in the identifier of the shared group.

Doctrine - I'm getting Entity class instead of Repository class

I create instance of entity manager
$this->em = Connection::MainMySql()->GetEntityManager();
After some queries I try to get object from a Repository class.
$usersArray = $this->em->createQueryBuilder()
->select("us")
->from('Model\Repo\mytables\User', "us")
->where("us.idUser = :idUser")
->setParameter("idUser", $idUser)
->getQuery()
->execute();
Why do I then get list of objects of class Model\Entity\mytables\User instead of Model\Repo\mytables\User even after I specify desired class in from(...) section?
In fact, a repository cannot be used as a representation of a database entry.
In other words, Repositories should contain methods to retrieve/create/update/delete database entries represented by entities.
This is why the EntityManager is called Entity Manager, it manages Entities and not Repository classes.
For instance, you can perfectly do:
// Return an instance of the Repository Model\Repo\mytables\User
$repository = $this->em->getRepository('Model\Entity\mytables\User');
// The repository is used to create the QueryBuilder, so the from statement is already filled by doctrine as model\Entity\mytables\User
$query = $repository->createQueryBuilder('u')
// ...
This is also why you can do:
$repository = $this->em->getRepository('Model\Entity\mytables\User');
// Return all entries of the 'users' table as Model\Entity\mytables\User instances
$users = $repository->findAll();
I'm surprised that the from statement of your query doesn't produce an error such as "Model\Entity\mytables\User is not a valid entity".
Also, your structure looks confusing, you must differentiate properly Repositories (the Models) from Entities in order to use them according to their respective roles.

zf2 acl doctrine 2

Actually using Zend Framework 2, I am looking for a way to implement a performant ACL strategy based on a database.
The whole idea is to directly filter the DQL queries depending on the currently logged in user, and it's permissions.
I found an implementation of this mecanisme in Symfony 2 http://symfony.com/doc/current/cookbook/security/acl_advanced.html, in this case one table seems to store for each user if he has access to a single row, so we can easily dynamically load only allowed rows by joining this table.
To synthesize,I am looking for a way to define access rules to entities based on criterias, but want to be able to get results in a single query to be able to do some ordering, and pagination.
Are there any ZF2 modules to resolve this case ?
It looks like integrating the SF2 security component as standalone is not an option: Security component from Symfony 2.0 as standalone
You have to use doctrine filter for load things for current member
example of my codes adding the filter for member query :
$em = $sm->get('doctrine.entitymanager.orm_default');
$ormconfig = $sm->get('doctrine.configuration.orm_default');
$ormconfig->addFilter("member", "\PatrickCore\Script\ORM\Functional\MemberAccessFilter");
//
$currentUser = $membersService->getCurrentUser();
$uid = $currentUser->getId();
$filter = $em->getFilters()->enable("member");
$filter->setParameter('member', $uid);
and this file \PatrickCore\Script\ORM\Functional\MemberAccessFilter :
<?php
namespace PatrickCore\Script\ORM\Functional;
use Doctrine\ORM\Mapping\ClassMetaData,
Doctrine\ORM\Query\Filter\SQLFilter;
class MemberAccessFilter extends SQLFilter
{
public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
// Check if the entity implements the LocalAware interface
if (!$targetEntity->reflClass->implementsInterface('\PatrickCore\Entity\MemberAccessAware')) {
return "";
}
return $targetTableAlias.'.member_id = ' . $this->getParameter('member'); // getParameter applies quoting automatically
}
}